Measuring time in C

aalf1987 picture aalf1987 · Oct 31, 2012 · Viewed 31.9k times · Source

I'm trying to measure some activity in C (Matrix multiplying) and noticed that I should do something like this:

clock_t start = clock();
sleep(3);
clock_t end = clock();
double elapsed_time = (end - start)/(double)CLOCKS_PER_SEC;
printf("Elapsed time: %.2f.\n", elapsed_time);

The output is:

Elapsed time: 0.00.

Why is this happening?

Answer

Fred Foo picture Fred Foo · Oct 31, 2012

clock estimates the CPU time used by your program; that's the time the CPU has been busy executing instructions belonging to your program. sleep doesn't perform any work, so it takes no noticeable CPU time (even if it takes wallclock time).

If you want to measure wallclock time, use time:

time_t start = time(NULL);
sleep(3);
printf("%.2f\n", (double)(time(NULL) - start));

will print a number close to three.