/* timing.c by R. Teather for COSC 2P91 * Simple exmaple of getting timing figure (in milliseconds) using * system time library. Note that C's timing features are notoriously * unreliable, and timing is not guarunteed. The gettimeofday function * provides time (somewhat unreliably) to nanosecond precision, unlike * the C standard time functions which are even less reliable. */ #include /*need POSIX-compliant time library*/ #include int main(void) { int i; long usTimeDiff = 0, sTimeDiff = 0; double msTimeDiff = 0; struct timeval t1, t2; gettimeofday(&t1, NULL); /* waste some time */ for(i = 0; i < 1000000000; i ++) ; gettimeofday(&t2, NULL); /* gettimeofday provides a structure with a separate * second and usec counter - need to get both * differences, then convert and sum them, and finally * convert the total time diff to ms */ sTimeDiff = t2.tv_sec - t1.tv_sec; usTimeDiff = t2.tv_usec - t1.tv_usec; msTimeDiff = ((sTimeDiff * 1000000) + usTimeDiff)/1000.0f; printf("Time diff (ms): %f \n\n", msTimeDiff); return 0; }