背景
有時我們在做開發的時候需要記錄每個任務執行時間,或者記錄一段代碼執行時間,最簡單的方法就是打印當前時間與執行完時間的差值,然后這樣如果執行大量測試的話就很麻煩,並且不直觀,如果想對執行的時間做進一步控制,則需要在程序中很多地方修改,目前spring-framework提供了一個StopWatch類可以做類似任務執行時間控制,也就是封裝了一個對開始時間,結束時間記錄操作的Java類,小例一則如下
實例
package com.example.stopwatch; import org.springframework.util.StopWatch; public class TestStopWatch { private void test() throws InterruptedException { StopWatch sw = new StopWatch(); sw.start("起床"); Thread.sleep(1000); sw.stop(); sw.start("洗漱"); Thread.sleep(2000); sw.stop(); sw.start("鎖門"); Thread.sleep(500); sw.stop(); System.out.println(sw.prettyPrint()); System.out.println(sw.getTotalTimeMillis()); System.out.println(sw.getLastTaskName()); System.out.println(sw.getLastTaskInfo()); System.out.println(sw.getTaskCount()); } public static void main(String []argv) throws InterruptedException { TestStopWatch testStopWatch = new TestStopWatch(); testStopWatch.test(); } }
結果
StopWatch '': running time (millis) = 3518 ----------------------------------------- ms % Task name ----------------------------------------- 00998 028% 起床 02020 057% 洗漱 00500 014% 鎖門 3518 鎖門 org.springframework.util.StopWatch$TaskInfo@5b2133b1 3