alopezf1987 alopezf1987 - 6 months ago 34
C Question

Measuring time in C

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

clock_t start = clock();
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 Source

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);
printf("%.2f\n", (double)(time(NULL) - start));

will print a number close to three.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download