計算程序運行時間


package org.tinygroup.demo;

public class Timing {
    public static double round(double value) {
        return Math.round(value * 10.0) / 10.0;// 利用Math類的round方法進行四舍五入計算
    }
    
    public static String getElapsedText(long elapsedMillis) {
        if (elapsedMillis < 60000) {
            double unit = round(elapsedMillis / 1000.0);// 將時間轉換成秒
            return unit + "秒";// 在轉換完的時間后增加單位
        } else if (elapsedMillis < 60000 * 60) {
            double unit = round(elapsedMillis / 60000.0);// 將時間轉換成分
            return unit + "分";// 在轉換完的時間后增加單位
        } else if (elapsedMillis < 60000 * 60 * 24) {
            double unit = round(elapsedMillis / (60000.0 * 60));// 將時間轉換成時
            return unit + "時";// 在轉換完的時間后增加單位
        } else {
            double unit = round(elapsedMillis / (60000.0 * 60 * 24));// 將時間轉換成天
            return unit + "天";// 在轉換完的時間后增加單位
        }
    }
    
    public static void main(String[] args) {
        long begin = System.currentTimeMillis();
        System.out.println("程序開始運行時間:" + begin);
        for (int i = 0; i < 1000000000; i++) {
            Math.random();
        }
        long end = System.currentTimeMillis();
        System.out.println("程序結束運行時間:" + end);
        System.out.println("程序運行時間:" + getElapsedText(end - begin));
    }
}

 

關鍵:

  通過System類獲取系統的當前時間。


免責聲明!

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



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