Best timing method in C?

lillq picture lillq · Jan 20, 2009 · Viewed 105.4k times · Source

What is the best way to time a code section with high resolution and portability?

/* Time from here */
ProcessIntenseFunction();
/* to here. */

printf("Time taken %d seconds %d milliseconds", sec, msec);

Is there a standard library that would have a cross-platform solution?

Answer

Sophie Alpert picture Sophie Alpert · Jan 20, 2009

I think this should work:

#include <time.h>

clock_t start = clock(), diff;
ProcessIntenseFunction();
diff = clock() - start;

int msec = diff * 1000 / CLOCKS_PER_SEC;
printf("Time taken %d seconds %d milliseconds", msec/1000, msec%1000);