System.currentTimeMillis vs System.nanoTime

后端 未结 10 1230
后悔当初
后悔当初 2020-11-21 22:56

Accuracy Vs. Precision

What I would like to know is whether I should use System.currentTimeMillis() or System.nanoTime()<

10条回答
  •  抹茶落季
    2020-11-21 23:18

    Update by Arkadiy: I've observed more correct behavior of System.currentTimeMillis() on Windows 7 in Oracle Java 8. The time was returned with 1 millisecond precision. The source code in OpenJDK has not changed, so I do not know what causes the better behavior.


    David Holmes of Sun posted a blog article a couple years ago that has a very detailed look at the Java timing APIs (in particular System.currentTimeMillis() and System.nanoTime()), when you would want to use which, and how they work internally.

    Inside the Hotspot VM: Clocks, Timers and Scheduling Events - Part I - Windows

    One very interesting aspect of the timer used by Java on Windows for APIs that have a timed wait parameter is that the resolution of the timer can change depending on what other API calls may have been made - system wide (not just in the particular process). He shows an example where using Thread.sleep() will cause this resolution change.

提交回复
热议问题