Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop time from running backwards on Linux?

Here's a little test I've written to verify that time does indeed only run forwards in Linux.

#include <time.h>
#include <sys/time.h>  

bool timeGoesForwardTest2()
{
   timeval tv1, tv2;   
   double startTime = getTimeSeconds();  // my function

   while ( getTimeSeconds() - startTime < 5 )
   {
      gettimeofday( &tv1, NULL );  
      gettimeofday( &tv2, NULL );  

      if ( tv2.tv_usec == tv1.tv_usec &&
           tv2.tv_sec == tv1.tv_sec )
      {
         continue;  // Equal times are allowed.
      }

      // tv2 should be greater than tv1
      if ( !( tv2.tv_usec>tv1.tv_usec ||
              tv2.tv_sec-1 == tv1.tv_sec ) )
      {
         printf( "tv1: %d %d\n", int( tv1.tv_sec ), int( tv1.tv_usec ) );
         printf( "tv2: %d %d\n", int( tv2.tv_sec ), int( tv2.tv_usec ) );
         return false;
      }         
   }
   return true;
}

Test fails with the result.

 tv1: 1296011067 632550
 tv2: 1296011067 632549

ummm....

Why does this happen?

Here's my setup:

Linux version 2.6.35-22-generic (buildd@rothera) (gcc version 4.4.5 (Ubuntu/Linaro 4.4.4-14ubuntu4) ) #33-Ubuntu SMP Sun Sep 19 20:34:50 UTC 2010 (Ubuntu 2.6.35-22.33-generic 2.6.35.4)
... running inside VirtualBox 3.2.12, in Windows 7.
like image 358
user48956 Avatar asked Jan 26 '11 03:01

user48956


4 Answers

gettimeofday() is not guaranteed to be monotonic. Use clock_gettime(CLOCK_MONOTONIC) if you need that guarantee.

like image 142
ephemient Avatar answered Nov 20 '22 21:11

ephemient


There is an open issue at the VirtualBox Bug Tracker. They link to a blog post stating why you shouldn't use gettimeofday() to measure the passage of time:

The most portable way to measure time correctly seems to be clock_gettime(CLOCK_MONOTONIC, ...)

like image 23
vz0 Avatar answered Nov 20 '22 19:11

vz0


Machine timers on most machines only have about 15 usec precision (even to native code). Time going 'backward' is odd, but you really can't rely on that level (1 usec) anyway. (Also note: there is a difference between precision and accuracy; the accuracy of most timers is worse than its precision). The use of a virtual machine may aggravate this as well.

Update: Typo

like image 39
phooji Avatar answered Nov 20 '22 20:11

phooji


It's not that it's running backwards. It'd be better to say that it is not reporting the correct time. This is because computers, without the aid of a dedicated timing subsystem, simply are not capable of reporting time very accurately in single millisecond intervals.

The precision will vary with hardware, the OS and even the power supply. Here is an article for starters. A bit old but communicates the idea nicely.

like image 5
Paul Sasik Avatar answered Nov 20 '22 21:11

Paul Sasik