System.currentTimeMillis vs System.nanoTime

后端 未结 10 1236
后悔当初
后悔当初 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:17

    Since no one else has mentioned this…

    It is not safe to compare the results of System.nanoTime() calls between different threads. Even if the events of the threads happen in a predictable order, the difference in nanoseconds can be positive or negative.

    System.currentTimeMillis() is safe for use between threads.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-21 23:18

    I've had good experience with nanotime. It provides wall-clock time as two longs (seconds since the epoch and nanoseconds within that second), using a JNI library. It's available with the JNI part precompiled for both Windows and Linux.

    0 讨论(0)
  • 2020-11-21 23:20

    Yes, if such precision is required use System.nanoTime(), but be aware that you are then requiring a Java 5+ JVM.

    On my XP systems, I see system time reported to at least 100 microseconds 278 nanoseconds using the following code:

    private void test() {
        System.out.println("currentTimeMillis: "+System.currentTimeMillis());
        System.out.println("nanoTime         : "+System.nanoTime());
        System.out.println();
    
        testNano(false);                                                            // to sync with currentTimeMillis() timer tick
        for(int xa=0; xa<10; xa++) {
            testNano(true);
            }
        }
    
    private void testNano(boolean shw) {
        long strMS=System.currentTimeMillis();
        long strNS=System.nanoTime();
        long curMS;
        while((curMS=System.currentTimeMillis()) == strMS) {
            if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)); }
            }
        if(shw) { System.out.println("Nano: "+(System.nanoTime()-strNS)+", Milli: "+(curMS-strMS)); }
        }
    
    0 讨论(0)
提交回复
热议问题