Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure user/system cpu time for a piece of program?

Tags:

c

unix

In section 3.9 of the classic APUE(Advanced Programming in the UNIX Environment), the author measured the user/system time consumed in his sample program which runs against varying buffer size(an I/O read/write program).

The result table goes kinda like(all the time are in the unit of second):

BUFF_SIZE  USER_CPU   SYSTEM_CPU  CLOCK_TIME  LOOPS
1          124.89     161.65      288.64      103316352
...        
512        0.27       0.41        7.03        201789
...

I'm curious about and really wondering how to measure the USER/SYSTEM CPU time for a piece of program?

And in this example, what does the CLOCK TIME mean and how to measure it?

Obviously it isn't simply the sum of user CPU time and system CPU time.

like image 834
snowfox Avatar asked Nov 02 '25 15:11

snowfox


1 Answers

You could easily measure the running time of a program using the time command under *nix:

$ time myprog

real        0m2.792s
user        0m0.099s
sys         0m0.200s

The real or CLOCK_TIME refers to the wall clock time i.e the time taken from the start of the program to finish and includes even the time slices taken by other processes when the kernel context switches them. It also includes any time, the process is blocked (on I/O events, etc.)

The user or USER_CPU refers to the CPU time spent in the user space, i.e. outside the kernel. Unlike the real time, it refers to only the CPU cycles taken by the particular process.

The sys or SYSTEM_CPU refers to the CPU time spent in the kernel space, (as part of system calls). Again this is only counting the CPU cycles spent in kernel space on behalf of the process and not any time it is blocked.

In the time utility, the user and sys are calculated from either times() or wait() system calls. The real is usually calculated using the time differences in the 2 timestamps gathered using the gettimeofday() system call at the start and end of the program.

One more thing you might want to know is real != user + sys. On a multicore system the user or sys or their sum can quite easily exceed the real time.

like image 109
Tuxdude Avatar answered Nov 04 '25 13:11

Tuxdude