Execution time of C program

Roger picture Roger · Mar 9, 2011 · Viewed 462.8k times · Source

I have a C program that aims to be run in parallel on several processors. I need to be able to record the execution time (which could be anywhere from 1 second to several minutes). I have searched for answers, but they all seem to suggest using the clock() function, which then involves calculating the number of clocks the program took divided by the Clocks_per_second value.

I'm not sure how the Clocks_per_second value is calculated?

In Java, I just take the current time in milliseconds before and after execution.

Is there a similar thing in C? I've had a look, but I can't seem to find a way of getting anything better than a second resolution.

I'm also aware a profiler would be an option, but am looking to implement a timer myself.

Thanks

Answer

Thomas Pornin picture Thomas Pornin · Mar 9, 2011

CLOCKS_PER_SEC is a constant which is declared in <time.h>. To get the CPU time used by a task within a C application, use:

clock_t begin = clock();

/* here, do your time-consuming job */

clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;

Note that this returns the time as a floating point type. This can be more precise than a second (e.g. you measure 4.52 seconds). Precision depends on the architecture; on modern systems you easily get 10ms or lower, but on older Windows machines (from the Win98 era) it was closer to 60ms.

clock() is standard C; it works "everywhere". There are system-specific functions, such as getrusage() on Unix-like systems.

Java's System.currentTimeMillis() does not measure the same thing. It is a "wall clock": it can help you measure how much time it took for the program to execute, but it does not tell you how much CPU time was used. On a multitasking systems (i.e. all of them), these can be widely different.