Thursday, April 14, 2011

Calculate Elapsed Time in C


We can use the function and structs in standard C library (sys/time.h) to calculate the elapsed time value between two time instances:

1. To get the processor time of the program, we use the C library clock_t struct to count the CPU clock ticks, and then divide the CLOCKS_PER_SEC to get the time:

    e.g.
        clock_t t;
        t = clock();   
        // Do something
        t = clock() - t;
        double cpu_time_elapsed = (double)t/CLOCKS_PER_SEC;


2. To calculate the time interval in wall clock time, use the C library time_t struct and the time difference function:
   
    double difftime(time_t end, time_t start)
   
  , where the start and end time can be initialized by calling time_t time(time_t *time) function, and the return value is the seconds (in double) elapsed between start and end.

    e.g.   
        time_t start, end;
        time(&start);
        // Do something
        time(&end);
        double time_elapsed = difftime(end, start);


3. To calculate the time interval more precisely (in higher resolution), we can define a C function like:

    double getTimeElapsed(struct timeval end, struct timeval start)
    {
        return (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000000.00;
    }

  , where the struct timeval is elapsed time declared in the sys/time.h. It contains two members:

        tv_sec (number of seconds elapsed)
       
  and
 
        tv_usec (remaining second fraction in microseconds).

    To get the start and end time value, we call the gettimeofday() function.
 
    e.g.
        timeval start, end;
        gettimeofday(&start, NULL);
        // Do something
        gettimeofday(&end, NULL);
        double time_elapsed = getTimeElapsed(end, start);

       
    Another time struct, timespec has two members tv_sec and tv_nsec, where tv_nsec represent remaining second fraction in nanosecond.
   

Reference: 
1. GNU C Library Manual: 21.2 Elapsed Time
2. difftime on cplusplus.com

No comments:

Post a Comment

(Coding && Eating) || Sleeping