使用 StopWatch 優(yōu)雅打印執(zhí)行耗時
0x01:背景
有時在做開發(fā)的時候需要記錄每個任務(wù)執(zhí)行時間,或者記錄一段代碼執(zhí)行時間,最簡單的方法就是打印當(dāng)前時間與執(zhí)行完時間的差值,然后這樣如果執(zhí)行大量測試的話就很麻煩,并且不直觀,如果想對執(zhí)行的時間做進(jìn)一步控制,則需要在程序中很多地方修改,目前spring-framework提供了一個StopWatch類可以做類似任務(wù)執(zhí)行時間控制,也就是封裝了一個對開始時間,結(jié)束時間記錄工具
示例
先來看幾個示例
- 統(tǒng)計輸出總耗時
- import org.springframework.util.StopWatch;
- public class SpringStopWatchExample {
- public static void main (String[] args) throws InterruptedException {
- StopWatch sw = new StopWatch();
- sw.start();
- //long task simulation
- Thread.sleep(1000);
- sw.stop();
- System.out.println(sw.getTotalTimeMillis());
- }
- }
輸出
- 1013
- 輸出最后一個任務(wù)的耗時
- public class SpringStopWatchExample2 {
- public static void main (String[] args) throws InterruptedException {
- StopWatch sw = new StopWatch();
- sw.start("A");//setting a task name
- //long task simulation
- Thread.sleep(1000);
- sw.stop();
- System.out.println(sw.getLastTaskTimeMillis());
- }
- }
輸出
- 1009
- 以優(yōu)雅的格式打出所有任務(wù)的耗時以及占比
- import org.springframework.util.StopWatch;
- public class SpringStopWatchExample3 {
- public static void main (String[] args) throws InterruptedException {
- StopWatch sw = new StopWatch();
- sw.start("A");
- Thread.sleep(500);
- sw.stop();
- sw.start("B");
- Thread.sleep(300);
- sw.stop();
- sw.start("C");
- Thread.sleep(200);
- sw.stop();
- System.out.println(sw.prettyPrint());
- }
- }
輸出
- StopWatch '': running time (millis) = 1031
- -----------------------------------------
- ms % Task name
- -----------------------------------------
- 00514 050% A
- 00302 029% B
- 00215 021% C:
- 序列服務(wù)輸出耗時信息
- @Override
- public long nextSeq(String name) {
- StopWatch watch = new StopWatch();
- watch.start("單序列獲取總消耗");
- long sequence = generator.generateId(name);
- watch.stop();
- logger.info(watch.prettyPrint());
- return sequence;
- }
0x02:更多用法
不同的打印結(jié)果
- getTotalTimeSeconds() 獲取總耗時秒,同時也有獲取毫秒的方法
- prettyPrint() 優(yōu)雅的格式打印結(jié)果,表格形式
- shortSummary() 返回簡短的總耗時描述
- getTaskCount() 返回統(tǒng)計時間任務(wù)的數(shù)量
- getLastTaskInfo().getTaskName() 返回最后一個任務(wù)TaskInfo對象的名稱
更多查看文檔
0x03:總結(jié)
以后統(tǒng)計代碼執(zhí)行效率建議大家都使用這個工具來進(jìn)行輸出,不需要在starttime、endtime再相減計算,用優(yōu)雅的方式來完成這件事情。