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

后端 未结 3 2038
醉酒成梦
醉酒成梦 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条回答
  •  Happy的楠姐
    2021-01-21 09:00

    The inconsistencies probably arise not from Java, but from the different OSs and VMs "atomic-" or system- clocks themselves.

    According to the official .nanoTime() documentation:

    no guarantees are made except that the resolution is at least as good as that of currentTimeMillis()

    source

    ...I can tell from personal knowledge that this is because in some OSs and VMs, the system itself doesn't support "atomic" clocks, which are necessary for higher resolutions. (I will post the link to source this information as soon as I find it again...It's been a long time.)

提交回复
热议问题