How can I measure time in Java not susceptible to System clock changes?

后端 未结 5 787
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 10:43

I would like to measure elapsed time in a Java. However differences in System.currentTimeMillis() and (I believe) System.nanoTime() can be changed

5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-03 11:43

    This doesn't really answer your question, but bug #6458294 implies that where possible, Sun's implementation of nanoTime() will use mechanisms which are truly monotonic (CLOCK_MONOTONIC on Linux, QueryPerformanceFrequency/QueryPerformanceCounter on Windows). Only if these are unavailable will it fall back to a mechanism which is susceptible to system clock changes.

    If you have control (or at least knowledge) of the hardware you're running on, and can ensure that these clock mechanisms will be available, you might be in luck and nanoTime() will do fine.

    You may also like to read this blog post, which discusses the HotSpot-on-Windows case in more detail.

提交回复
热议问题