Contrary to popular belief, the clock()
function retrieves CPU time, not elapsed clock time as the name confusingly may induce people to believe.
Here is the language from the C Standard:
7.27.2.1 The clock
function
Synopsis
#include <time.h>
clock_t clock(void);
Description
The clock
function determines the processor time used.
Returns
The clock
function returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation. To determine the time in seconds, the value returned by the clock function should be divided by the value of the macro CLOCKS_PER_SEC
. If the processor time used is not available, the function returns the value (clock_t)(−1)
. If the value cannot be represented, the function returns an unspecified value.
To retrieve the elapsed time, you should use one of the following:
- the
time()
function with a resolution of 1 second
- the
timespec_get()
function which may be more precise, but might not be available on all systems
- the
gettimeofday()
system call available on linux systems
- the
clock_gettime()
function.
See What specifically are wall-clock-time, user-cpu-time, and system-cpu-time in UNIX? for more information on this subject.
Here is a modified version using gettimeoday()
:
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
int main() {
struct timeval start, end;
gettimeofday(&start, NULL);
sleep(3);
gettimeofday(&end, NULL);
double time_taken = end.tv_sec + end.tv_usec / 1e6 -
start.tv_sec - start.tv_usec / 1e6; // in seconds
printf("time program took %f seconds to execute\n", time_taken);
return 0;
}
Output:
time program took 3.005133 seconds to execute