Should you be using monotonic timers?

Posted by Cliff Brake on 2009-01-09 | Comments are off for this article

In a previous article ( ), I covered some of the basics of Linux timers.  Any time you are doing any type of fixed time delay in a program, you should really be using monotonic times, so the delay will not be affected by system time changes.  In an effort to save cost, some embedded systems today do not have a battery backed up RTC, and instead get the time via GPS, NTP servers, or other clever means.  What this means is your applications had better be able to handle the system time changing as the system time may not be set until well after the unit boots.  This article describes how you can quickly test your system for timer problems.

There are two cases where delays may fail if you are using non-monotonic timers.  The first is if the time advances forward by a large amount.  Delays will expire immediately in this case.  The other case is if the time advances backward by a large amount.  Delays will never expire in this case.  To test for these situations, write a simple test application (sample included below) that rapidly changes the time and then test your application while the time is changing.

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

int main()
  time_t system_time;
  static int count = 0;

  printf("Starting test application...\n");
    // Sleep for 0.01 seconds
    usleep(10 * 1000);

    system_time = time(NULL);
    system_time += 30;
    printf("Cycle %d - system date/time set to %s", ++count, ctime(&system_time));

Comments are closed.