next up previous
Next: About this document ... Up: intro_C Previous: Random Numbers

Timers

The library calls gettimeofday(), time(), clock(), times(), and getrusage() can all be used to measure execution times. The best resolution is obtained from gettimeofday() (for wallclock) and getrusage() (for user and system). Both these functions take structure pointers as arguments and fill the elements with timer values. The best strategy for all such timers is to difference the before and after values. Check the man pages for more info. Note the crucial difference between wallclock and user/system time is that the former will increase as the load on the machine increases due to other processes whereas the latter will not. Here's a simple example using clock(), which returns the amount of CPU time used so far:

    #include <stdio.h>
    #include <time.h>

    double getCPU(void)
    {
        return (double) clock()/CLOCKS_PER_SEC; /* convert to seconds */
    }

    int main(void)
    {
        double t0,dt;
        t0 = getCPU();         /* get initial value */
        MyExpensiveFunction();
        dt = getCPU() - t0;    /* difference to get execution time */
        (void) printf("Execution time: %g sec\n",dt);
        return 0;
    }



Massimo Ricotti 2009-01-26