Determine Elapsed Time using Monotonic Clocks in Linux


TiIf a program requires measuring elapsed time, you will need an individual timer that will be independent even if the user changes the time on the system clock. In Linux there are several different implementations for different cases (

    System-wide realtime clock. Setting this clock requires appropriate privileges.
    Clock that cannot be set and represents monotonic time since some unspecified starting point.
    High-resolution per-process timer from the CPU.
    Thread-specific CPU-time clock.

To safely measure the elapsed time, you need a clock that ticks out time continuously, without any jumps when a user sets the system time. This kind of clock is called a monotonic clock. (CLOCK_MONOTONIC or CLOCK_MONOTONIC_RAW which gives more accurate results over very short intervals)

#include <time.h>

/* ... */

struct timespec get_elapsed_time(struct timespec* start,struct timespec* stop)
  struct timespec elapsed_time;
  if ((stop->tv_nsec - start->tv_nsec) < 0) 
    elapsed_time.tv_sec = stop->tv_sec - start->tv_sec - 1;
    elapsed_time.tv_nsec = stop->tv_nsec - start->tv_nsec + 1000000000;
    elapsed_time.tv_sec = stop->tv_sec - start->tv_sec;
    elapsed_time.tv_nsec = stop->tv_nsec - start->tv_nsec;
  return elapsed_time;

  /* ... */

  struct timespec start;
  struct timespec stop;
  struct timespec elapsed_time;

  if(clock_gettime(CLOCK_MONOTONIC, &start))
  { /* handle error */ }

  /* Do stuff */

  if(clock_gettime(CLOCK_MONOTONIC, &stop))
  { /* handle error */ }

  elapsed_time = get_elapsed_time(&start,&stop);

  /* ... */


Add comment



Subscribe to our Newsletter