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.
clock
function.
CLOCKS_PER_SEC
.
clock
function. Values of type clock_t
are in units of clock ticks.
clock
returns the value (clock_t)(-1)
.