Clock drift on Windows

后端 未结 13 718
无人共我
无人共我 2020-12-28 18:42

I\'ve developed a Windows service which tracks business events. It uses the Windows clock to timestamp events. However, the underlying clock can drift quite dramatically (e.

13条回答
  •  温柔的废话
    2020-12-28 19:12

    I don't know if this applies, but ...

    There's an issue with Windows that if you change the timer resolution with timeBeginPeriod() a lot, the clock will drift.

    Actually, there is a bug in Java's Thread wait() (and the os::sleep()) function's Windows implementation that causes this behaviour. It always sets the timer resolution to 1 ms before wait in order to be accurate (regardless of sleep length), and restores it immediately upon completion, unless any other threads are still sleeping. This set/reset will then confuse the Windows clock, which expects the windows time quantum to be fairly constant.

    Sun has actually known about this since 2006, and hasn't fixed it, AFAICT!

    We actually had the clock going twice as fast because of this! A simple Java program that sleeps 1 millisec in a loop shows this behaviour.

    The solution is to set the time resolution yourself, to something low, and keep it there as long as possible. Use timeBeginPeriod() to control that. (We set it to 1 ms without any adverse effects.)

    For those coding in Java, the easier way to fix this is by creating a thread that sleeps as long as the app lives.

    Note that this will fix this issue on the machine globally, regardless of which application is the actual culprit.

提交回复
热议问题