How to stop time from running backwards on Linux?

后端 未结 5 1115
情书的邮戳
情书的邮戳 2021-02-12 11:15

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

#include 
#include   

bool timeG         


        
相关标签:
5条回答
  • 2021-02-12 11:30

    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

    0 讨论(0)
  • 2021-02-12 11:39

    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.

    0 讨论(0)
  • 2021-02-12 11:49

    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, ...)

    0 讨论(0)
  • 2021-02-12 11:49

    Time should not run backwards on real hardware; on a VM your mileage may vary.

    In any case, your application should probably not assume that time doesn't run backwards by a very small amount (think, maybe 1 second).

    Yes, clock_gettime is good but even that could run backwards in the case of faulty hardware (or a VM, as in your example).

    I have seen a hardware bug make time run backwards (albeit very occasionally), it was a cause of some very peculiar problems.

    In particular, anything which involves comparing file timestamps will go wrong when time goes backwards.

    0 讨论(0)
  • 2021-02-12 11:50

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

    0 讨论(0)
提交回复
热议问题