System.nanoTime與System.currentTimeMillis的區別


 

System.nanoTime提供相對精確的計時,以納秒為單位,常在產生隨機數函數以及線程池中的一些函數使用.

public class SystemTimeTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        long startTime = System.nanoTime();
        createStringBuilder();
        long estimatedTime = System.nanoTime() - startTime;
        System.out.println(estimatedTime);  //1s=1000毫秒=1000000微秒=1000000000納秒
        
    }
    
    /**
     * 測試StringBuilder執行一萬次增加和清除字符串所花時間
     */
    private static void createStringBuilder() {
        StringBuilder sb = new StringBuilder();
        for(int i = 1; i <= 10000; i++){
            sb.append("Hello World");
            sb.delete(0, sb.length());
        }
        
    }

}


//運行結果:4713503

 

 

System.currentTimeMillis單位毫秒,那么每次的結果將會差別很小,甚至一樣,因為現代的計算機運行速度很快

 

public class SystemTimeTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        
        long startTime = System.currentTimeMillis();
        createStringBuilder();
        long estimatedTime = System.currentTimeMillis() - startTime;
        System.out.println(estimatedTime);  //1s=1000毫秒=1000000微秒=1000000000納秒
        
    }
    
    /**
     * 測試StringBuilder執行一萬次增加和清除字符串所花時間
     */
    private static void createStringBuilder() {
        StringBuilder sb = new StringBuilder();
        for(int i = 1; i <= 10000; i++){
            sb.append("Hello World");
            sb.delete(0, sb.length());
        }
        
    }

}

//運行結果:4

 

總結:nanoTime更細更精確,可用於線程中,currentTimeMillis可用來計算當前日期(精確到毫秒),星期幾等,可以方便的與Date進行轉換,用的時候根據需要取之.

參考文檔:https://blog.csdn.net/dliyuedong/article/details/8806868

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM