/* ** $Id: timing.c 819 2008-03-09 17:41:59Z phf $ ** ** Example for using time(3) and gettimeofday(2) to measure ** performance of pieces of code. You should probably use ** gprof instead, but hey... :-) ** ** Note that (on my machine) the timeval microseconds stuff ** sometimes returns crazy values; apparently you sometimes ** need to "round" those into the seconds field, but I won't ** bother here. For example, I found this piece of code on ** the net that explains better what I mean: ** ** // resolve seconds carry ** static inline void update_tv(struct timeval *t1) ** { ** if (t1->tv_usec >= MILLION_I) { ** t1->tv_sec++; ** t1->tv_usec -= MILLION_I; ** } ** if (t1->tv_usec < 0) { ** t1->tv_sec--; ** t1->tv_usec += MILLION_I; ** } ** } ** ** However, I could not find "proper" documentation on this ** anywhere... :-/ If you find something, let me know! :-) */ #include #include #include #include // just some code that runs a little while, if your machine // is faster, adjust the numbers... :-) void bla(void) { for (long i = 0; i < 0x07ffffff; i++) { // bla } } // not very exact: using time(3) function, seconds accuracy int timet(void) { time_t before, after; before = time(NULL); bla(); after = time(NULL); return after-before; } // much more exact: using gettimeofday(2) function, closer // to microseconds accuracy (but never really quite that) struct timeval timeg(void) { struct timeval before, after, difference; (void) gettimeofday(&before, NULL); bla(); (void) gettimeofday(&after, NULL); difference.tv_sec = after.tv_sec - before.tv_sec; difference.tv_usec = after.tv_usec - before.tv_usec; return difference; } int main(void) { printf("time(3) says: %d seconds\n", timet()); struct timeval time = timeg(); printf("gettimeofday(2) says: %ld seconds %ld microseconds\n", time.tv_sec, time.tv_usec); return EXIT_SUCCESS; }