Find the Elapsed Time using Monotonic Clocks in Linux

F

When a linux program requires measuring elapsed time, you need an individual timer to perform this task. This timer should be independent even if the user changes the time on the system clock. In Linux there are several different implementations for different cases (https://linux.die.net/man/3/clock_gettime):

  • 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.

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;
  } 
  else 
  {
    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);

  /* ... */

Disclaimer: The present content may not be used for training artificial intelligence or machine learning algorithms. All other uses, including search, entertainment, and commercial use, are permitted.

Categories

Tags