使用spring-framework的StopWatch類優雅的輸出執行耗時

      記錄一段程序執行時間,最簡單的方法就是打印當前時間與執行完時間的差值,其實這樣並且不直觀,目前spring-framework提供了一個StopWatch類可以做類似任務執行時間控制,也就是封裝了一個對開始時間,結束時間記錄工具。

 

例子

import org.springframework.util.StopWatch;
 
public class StopWatchTest {
 
    public static void main (String[] args) throws InterruptedException {
        StopWatch sw = new StopWatch();
        sw.start();
        //模擬程序執行
        Thread.sleep(1000);
        sw.stop();
        //輸出程序執行的秒數
        System.out.println(sw.getTotalTimeMillis());
        System.out.println("+++++++++++++++++++++++++++++");

        //輸出程序執行的毫秒數
        System.out.println(sw.getTotalTimeMillis());
        System.out.println("+++++++++++++++++++++++++++++");

        //優雅的格式打印結果,表格形式
        System.out.println(sw.prettyPrint());
        System.out.println("+++++++++++++++++++++++++++++");

        //返回簡短的總耗時描述
        System.out.println(sw.shortSummary());
    }
}

輸出

2002
+++++++++++++++++++++++++++++


2.002
+++++++++++++++++++++++++++++


StopWatch '': running time (millis) = 2002
-----------------------------------------
ms     %     Task name
-----------------------------------------
02002  100%  


+++++++++++++++++++++++++++++
StopWatch '': running time (millis) = 2002

是不是用起來簡捷又方便。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章