Measuring elapsed time in linux for a c program

Three alternatives

  1. clock()
  2. gettimeofday()
  3. clock_gettime()

clock_gettime() goes upto nanosecond accuracy and it supports 4 clocks.

  • CLOCK_REALTIME

    System-wide realtime clock. Setting this clock requires appropriate privileges.

  • CLOCK_MONOTONIC

    Clock that cannot be set and represents monotonic time since some unspecified starting point.

  • CLOCK_PROCESS_CPUTIME_ID

    High-resolution per-process timer from the CPU.

  • CLOCK_THREAD_CPUTIME_ID

    Thread-specific CPU-time clock.

You can use it as

#include <time.h>

struct timespec start, stop;

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);

/// do something

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &stop);

double result = (stop.tv_sec - start.tv_sec) * 1e6 + (stop.tv_nsec - start.tv_nsec) / 1e3;    // in microseconds

Note: The clock() function returns CPU time for your process, not wall clock time. I believe this is what the OP was interested in. If wall clock time is desired, then gettimeofday() is a good choice as suggested by an earlier answer. clock_gettime() can do either one if your system supports it; on my linux embedded system clock_gettime() is not supported, but clock() and gettimeofday() are.

Below is the code for getting wall clock time using gettimeofday()

#include <stdio.h> // for printf()
#include <sys/time.h> // for clock_gettime()
#include <unistd.h> // for usleep()

int main() {
    struct timeval start, end;
    long secs_used,micros_used;

    gettimeofday(&start, NULL);
    usleep(1250000); // Do the stuff you want to time here
    gettimeofday(&end, NULL);

    printf("start: %d secs, %d usecs\n",start.tv_sec,start.tv_usec);
    printf("end: %d secs, %d usecs\n",end.tv_sec,end.tv_usec);

    secs_used=(end.tv_sec - start.tv_sec); //avoid overflow by subtracting first
    micros_used= ((secs_used*1000000) + end.tv_usec) - (start.tv_usec);

    printf("micros_used: %d\n",micros_used);
    return 0;
}

To start with you need to use floating point arithmetics. Any integer value divided by a larger integer value will be zero, always.

And of course you should actually do something between getting the start and end times.


By the way, if you have access to gettimeofday it's normally preferred over clock as it has higher resolution. Or maybe clock_gettime which has even higher resolution.

Tags:

Linux

Time

C