StopWatch對應的中文名稱為秒表,經常我們對一段代碼耗時檢測的代碼如下:
long startTime = System.currentTimeMillis();
// 你的業務代碼
long endTime = System.currentTimeMillis();
long costTime = endTime -startTime;
System.err.println("該段代碼耗時:" + costTime + " ms");
改進的代碼寫法:
我們可以利用已有的工具類中的秒表,常見的秒表工具類有org.springframework.util.StopWatch、org.apache.commons.lang.time.StopWatch以及谷歌提供的guava中的秒表(這個我沒怎么用過)。這里重點講下,org.springframework.util.StopWatch的用法。
org.springframework.util.StopWatch的用法:
查看其源碼:
public class StopWatch {
private final String id;
private boolean keepTaskList;
private final List<StopWatch.TaskInfo> taskList;
private long startTimeMillis;
private boolean running;
private String currentTaskName;
private StopWatch.TaskInfo lastTaskInfo;
private int taskCount;
private long totalTimeMillis;
...
}
可以看到有一個List<StopWatch.TaskInfo> taskList,用於存儲一組任務的耗時時間。這個很有用比如:我們可以記錄多段代碼耗時時間,然后一次性打印(這里:org.springframework.util.StopWatch提供了一個prettyString()函數用於按照指定格式打印出耗時)
舉個例子:
public static void main(String[] args) throws InterruptedException {
// 定義一個計數器
StopWatch stopWatch = new StopWatch("統一一組任務耗時");
// 統計任務一耗時
stopWatch.start("任務一");
Thread.sleep(1000);
stopWatch.stop();
// 統計任務二耗時
stopWatch.start("任務二");
Thread.sleep(2000);
stopWatch.stop();
// 打印出耗時
String result = stopWatch.prettyPrint();
System.err.println(result);
}
結果為:
StopWatch '統一一組任務耗時': running time (millis) = 3000
-----------------------------------------
ms % Task name
-----------------------------------------
01000 033% 任務一
02000 067% 任務二
分析:
可以看到可以統一定義一個計數器為“統一一組任務耗時”,然后看到整段代碼的耗時。以及各個部分程序代碼的執行時間,並且輸出的格式幫我們整理好了。