c++ - How to stop time from running backwards on Linux? -
here's little test i've written verify time indeed run forwards in linux.
#include <time.h> #include <sys/time.h> bool timegoesforwardtest2() { timeval tv1, tv2; double starttime = gettimeseconds(); // 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 allowed. } // tv2 should greater 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 result.
tv1: 1296011067 632550 tv2: 1296011067 632549
ummm....
why happen?
here's 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.
there open issue @ virtualbox bug tracker. link blog post stating why you shouldn't use gettimeofday() measure passage of time:
the portable way measure time correctly seems clock_gettime(clock_monotonic, ...)
Comments
Post a Comment