System.currentTimeMillis vs System.nanoTime

后端 未结 10 1232
后悔当初
后悔当初 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: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)); }
        }
    

提交回复
热议问题