Go to the first, previous, next, last section, table of contents.


Basic CPU Time Inquiry

To get the elapsed CPU time used by a process, you can use the clock function. This facility is declared in the header file `time.h'.

In typical usage, you call the clock function at the beginning and end of the interval you want to time, subtract the values, and then divide by CLOCKS_PER_SEC (the number of clock ticks per second), like this:

#include <time.h>

clock_t start, end;
double elapsed;

start = clock();
... /* Do the work. */
end = clock();
elapsed = ((double) (end - start)) / CLOCKS_PER_SEC;

Different computers and operating systems vary wildly in how they keep track of processor time. It's common for the internal processor clock to have a resolution somewhere between hundredths and millionths of a second.

In the GNU system, clock_t is equivalent to long int and CLOCKS_PER_SEC is an integer value. But in other systems, both clock_t and the type of the macro CLOCKS_PER_SEC can be either integer or floating-point types. Casting processor time values to double, as in the example above, makes sure that operations such as arithmetic and printing work properly and consistently no matter what the underlying representation is.

Macro: int CLOCKS_PER_SEC
The value of this macro is the number of clock ticks per second measured by the clock function.

Macro: int CLK_TCK
This is an obsolete name for CLOCKS_PER_SEC.

Data Type: clock_t
This is the type of the value returned by the clock function. Values of type clock_t are in units of clock ticks.

Function: clock_t clock (void)
This function returns the elapsed processor time. The base time is arbitrary but doesn't change within a single process. If the processor time is not available or cannot be represented, clock returns the value (clock_t)(-1).


Go to the first, previous, next, last section, table of contents.