Tuesday, April 19, 2011

Time measure in C - clock() function

This C time measure example code that uses clock() function.Though clockt() function does not exactly count the number of cycles, it provides real-life numbers for performance of the code fragment. Note: In Windows, you can also use GetTickCount() function for time measure.



// Time measure routine using clock() function.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <time.h>

int main() {
clock_t start, stop;
double t = 0.0;

/* Start timer */
assert((start = clock())!=-1);

/* Do lotsa fancy calculations */

/* Stop timer */
stop = clock();
t = (double) (stop-start)/CLOCKS_PER_SEC;

printf("Run time: %f\n", t);

return(0);
} /* main */