Accuracy of System.nanoTime() to measure time elapsed decreases after a call to Thread.sleep()

后端 未结 3 2011
醉酒成梦
醉酒成梦 2021-01-21 08:38

I\'m encountering a really unusual issue here. It seems that the calling of Thread.sleep(n), where n > 0 would cause the following System.nanoTime() calls to be less predictable

3条回答
  •  无人共我
    2021-01-21 09:08

    I can suggest at least two possible reasons of such behavior:

    1. Power saving. When executing a busy loop, CPU runs at its maximum performance state. However, after Thread.sleep it is likely to fall into one of power-saving states, with frequency and voltage reduced. After than CPU won't return to its maximum performance immediately, this may take from several nanoseconds to microseconds.
    2. Scheduling. After a thread is descheduled due to Thread.sleep, it will be scheduled for execution again after a timer event which might be related to the timer used for System.nanoTime.

    In both cases you can't directly work around this - I mean Thread.sleep will also affect timings in your real application. But if the amount of useful work measured is large enough, the inaccuracy will be negligible.

提交回复
热议问题