Just a post to confirm Matthew's correct answer. The accuracy of Thread.Sleep()
is affected by the clock interrupt rate on Windows. It by default ticks 64 times per second, once every 15.625 msec. A `Sleep() can only complete when such an interrupt occurs. The mental image here is the one induced by the word "sleep", the processor is in fact asleep and not executing code. Only that clock interrupt is going to wake it up again to resume executing your code.
Your choice of 1000/60
was a very unhappy one, that asks for 16 msec. Just a bit over 15.625
so you'll always wake back up at least 2 ticks later: 2 x 15.625 = 31 msec
. What you measured.
That interrupt rate is however not fixed, it can be altered by a program. It does so by calling CreateTimerQueueTimer()
or the legacy timeBeginPeriod()
. A browser in general has a need to do so. Something simple as animating a GIF requires a better timer since GIF frame times are specified with a unit of 10 msec. Or in general any multi-media related operation needs it.
A very ugly side-effect of a program doing this is that this increased clock interrupt rate has system-wide effects. Like it did in your program. Your timer suddenly got accurate and you actually got the sleep duration you asked for, 16 msec. So Chrome is changing the rate to, probably, 1000 ticks per second. The maximum supported. And good for business when you have a competing operating system.
You can avoid this problem by picking a sleep duration that's a closer match to the default interrupt rate. If you ask for 15 then you'll get 15.625 and Chrome cannot have an effect on that. 31 is the next sweet spot. Etcetera, integer multiples of 15.625 and rounded down.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…