使用 StopWatch 優(yōu)雅打印執(zhí)行耗時
點擊下方“IT牧場”,選擇“設(shè)為星標(biāo)”

0x01:背景
有時在做開發(fā)的時候需要記錄每個任務(wù)執(zhí)行時間,或者記錄一段代碼執(zhí)行時間,最簡單的方法就是打印當(dāng)前時間與執(zhí)行完時間的差值,然后這樣如果執(zhí)行大量測試的話就很麻煩,并且不直觀,如果想對執(zhí)行的時間做進(jìn)一步控制,則需要在程序中很多地方修改,目前spring-framework提供了一個StopWatch類可以做類似任務(wù)執(zhí)行時間控制,也就是封裝了一個對開始時間,結(jié)束時間記錄工具
示例
先來看幾個示例
統(tǒng)計輸出總耗時
1import?org.springframework.util.StopWatch;
2
3public?class?SpringStopWatchExample?{
4
5????public?static?void?main?(String[]?args)?throws?InterruptedException?{
6????????StopWatch?sw?=?new?StopWatch();
7????????sw.start();
8????????//long?task?simulation
9????????Thread.sleep(1000);
10????????sw.stop();
11????????System.out.println(sw.getTotalTimeMillis());
12????}
13}輸出
11013輸出最后一個任務(wù)的耗時
1public?class?SpringStopWatchExample2?{
2
3????public?static?void?main?(String[]?args)?throws?InterruptedException?{
4????????StopWatch?sw?=?new?StopWatch();
5????????sw.start("A");//setting?a?task?name
6????????//long?task?simulation
7????????Thread.sleep(1000);
8????????sw.stop();
9????????System.out.println(sw.getLastTaskTimeMillis());
10????}
11}
輸出
11009以優(yōu)雅的格式打出所有任務(wù)的耗時以及占比
1import?org.springframework.util.StopWatch;
2
3public?class?SpringStopWatchExample3?{
4
5????public?static?void?main?(String[]?args)?throws?InterruptedException?{
6????????StopWatch?sw?=?new?StopWatch();
7????????sw.start("A");
8????????Thread.sleep(500);
9????????sw.stop();
10????????sw.start("B");
11????????Thread.sleep(300);
12????????sw.stop();
13????????sw.start("C");
14????????Thread.sleep(200);
15????????sw.stop();
16????????System.out.println(sw.prettyPrint());
17????}
18}輸出
1StopWatch?'':?running?time?(millis)?=?1031
2-----------------------------------------
3ms?????%?????Task?name
4-----------------------------------------
500514??050%??A
600302??029%??B
700215??021%??C:序列服務(wù)輸出耗時信息
1@Override
2public?long?nextSeq(String?name)?{
3????StopWatch?watch?=?new?StopWatch();
4????watch.start("單序列獲取總消耗");
5????long?sequence?=?generator.generateId(name);
6????watch.stop();
7????logger.info(watch.prettyPrint());
8????return?sequence;
9}0x02:更多用法
不同的打印結(jié)果
getTotalTimeSeconds() 獲取總耗時秒,同時也有獲取毫秒的方法
prettyPrint() 優(yōu)雅的格式打印結(jié)果,表格形式
shortSummary() 返回簡短的總耗時描述
getTaskCount() 返回統(tǒng)計時間任務(wù)的數(shù)量
getLastTaskInfo().getTaskName() 返回最后一個任務(wù)TaskInfo對象的名稱
更多查看文檔
1https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/util/StopWatch.html
0x03:總結(jié)
以后統(tǒng)計代碼執(zhí)行效率建議大家都使用這個工具來進(jìn)行輸出,不需要在starttime、endtime再相減計算,用優(yōu)雅的方式來完成這件事情。
source://ningyu1.github.io/20190505/116-stop-watch.html
干貨分享
最近將個人學(xué)習(xí)筆記整理成冊,使用PDF分享。關(guān)注我,回復(fù)如下代碼,即可獲得百度盤地址,無套路領(lǐng)??!
?001:《Java并發(fā)與高并發(fā)解決方案》學(xué)習(xí)筆記;?002:《深入JVM內(nèi)核——原理、診斷與優(yōu)化》學(xué)習(xí)筆記;?003:《Java面試寶典》?004:《Docker開源書》?005:《Kubernetes開源書》?006:《DDD速成(領(lǐng)域驅(qū)動設(shè)計速成)》?007:全部?008:加技術(shù)群討論
加個關(guān)注不迷路
喜歡就點個"在看"唄^_^
