別再用 System.currentTimeMillis 統(tǒng)計(jì)耗時(shí)了,太LOW,這個(gè)工具類(lèi)好用到爆!

作者:沉默王二
Java 程序員進(jìn)階之路:https://tobebetterjavaer.com
大家好,我是二哥呀!
昨天,二哥的編程星球里的一位球友問(wèn)我能不能給他解釋一下@SpringBootApplication注解是什么意思,還有 Spring Boot 的運(yùn)行原理,于是我就帶著他扒拉了一下這個(gè)注解的源碼,還有SpringApplication類(lèi)的run()方法的源碼,一下子他就明白了。
你別說(shuō),看源碼的過(guò)程還真的是挺有趣,這不,我就發(fā)現(xiàn)了一個(gè)有意思的點(diǎn)。
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ...... stopWatch.stop(); }
Spring Boot 是用 StopWatch 來(lái)統(tǒng)計(jì)耗時(shí)的,而通常情況下,我們會(huì)用System.currentTimeMillis()來(lái)統(tǒng)計(jì)耗時(shí),對(duì)吧?編程喵????開(kāi)源項(xiàng)目里就有這樣一段代碼,在處理統(tǒng)一日志處理切面的時(shí)候。
@Around("webLog()") public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable { long startTime = System.currentTimeMillis(); long endTime = System.currentTimeMillis(); webLog.setSpendTime((int) (endTime - startTime)); }
對(duì)比之下,我們就能發(fā)現(xiàn),JDK 提供的System.currentTimeMillis()沒(méi)有 Spring 提供的 StopWatch 簡(jiǎn)潔、清晰。
尤其是在多任務(wù)的情況下,StopWatch 簡(jiǎn)直好用到爆????!
// 創(chuàng)建一個(gè) StopWatch 實(shí)例 StopWatch sw = new StopWatch("沉默王二是傻 X"); // 開(kāi)始計(jì)時(shí) sw.start("任務(wù)1"); Thread.sleep(1000); // 停止計(jì)時(shí) sw.stop(); System.out.printf("任務(wù)1耗時(shí):%d%s.\n", sw.getLastTaskTimeMillis(), "ms"); sw.start("任務(wù)2"); Thread.sleep(1100); sw.stop(); System.out.printf("任務(wù)2耗時(shí):%d%s.\n", sw.getLastTaskTimeMillis(), "ms"); System.out.printf("任務(wù)數(shù)量:%s,總耗時(shí):%ss.\n", sw.getTaskCount(), sw.getTotalTimeSeconds());
看到?jīng)],是不是很簡(jiǎn)單?
- 先 new 一個(gè) StopWatch 對(duì)象
- 再 start 開(kāi)始計(jì)時(shí)
- 然后 stop 停止計(jì)時(shí)
- 最后通過(guò)sw.getLastTaskTimeMillis()得出時(shí)間差
如果換成System.currentTimeMillis()就要了老命,先得聲明好幾個(gè) long 型的局部變量,然后要第二個(gè)減第一個(gè),第三個(gè)減第二個(gè),稍微粗心一點(diǎn)(尤其是 CV 大法)時(shí),很容易搞錯(cuò)。
除了可以通過(guò)局部時(shí)間,還可以通過(guò)sw.getTotalTimeSeconds()獲取總的耗時(shí)。
任務(wù)1耗時(shí):1002ms. 任務(wù)2耗時(shí):1105ms. 任務(wù)數(shù)量:2,總耗時(shí):2.107820109s.
另外,StopWatch 還提供了一個(gè)sw.prettyPrint()方法供打印出漂亮的格式化結(jié)果:
StopWatch '沉默王二是傻 X': running time = 2108529351 ns
---------------------------------------------
ns % Task name
---------------------------------------------
1004338467 048% 任務(wù)1
1104190884 052% 任務(wù)2
有耗時(shí),有占用百分比,還有任務(wù)名,非常清晰。
除了 Spring,hutool 工具庫(kù)和 Apache common 工具包都提供了各自的 StopWatch。

查看 hutool 工具庫(kù)中的 StopWatch 源碼可以得出,該類(lèi)其實(shí)就來(lái)自 Spring 的 StopWatch.java,用法也完全一致。

這說(shuō)明 hutool 的作者也認(rèn)為 Spring 的 StopWatch 寫(xiě)得好,哈哈哈????。
使用 Beyond compare 比較后也能得出,兩者除了一個(gè)中文注釋?zhuān)粋€(gè)英文注釋?zhuān)a幾乎一樣。setKeepTaskList 方法有比較大的不同。

那也就是說(shuō),如果你的項(xiàng)目中沒(méi)有使用 Spring 全家桶,只用了 hutool 工具包,那就可以使用 hutool 的 StopWatch 來(lái)代替System.currentTimeMillis()。
通過(guò)分析 StopWatch 的 stop 方法源碼:
public void stop() throws IllegalStateException { if (null == this.currentTaskName) { throw new IllegalStateException("Can't stop StopWatch: it's not running"); } final long lastTime = System.nanoTime() - this.startTimeNanos; this.totalTimeNanos += lastTime; this.lastTaskInfo = new TaskInfo(this.currentTaskName, lastTime); if (null != this.taskList) { this.taskList.add(this.lastTaskInfo); } ++this.taskCount; this.currentTaskName = null; }
其實(shí)可以發(fā)現(xiàn),StopWatch 的內(nèi)部是通過(guò)System.nanoTime()來(lái)計(jì)時(shí)的,本質(zhì)上和System.currentTimeMillis()差別并不大。
nanoTime 比 currentTimeMillis 的粒度更細(xì),前者是以納秒為單位,后者是以毫秒為單位。

注意兩者都是 native 方法,也就是說(shuō),值的粒度其實(shí)取決于底層的操作系統(tǒng)。
看到這,大家可能會(huì)恍然大悟,StopWatch 不過(guò)是披著一層外衣的System.currentTimeMillis()嘛?
但妙就妙在,這層外衣足夠的漂亮,足夠的優(yōu)雅。StopWatch 可以記錄每個(gè)子任務(wù)的名稱(chēng),以及按格式化打印結(jié)果,尤其是針對(duì)多任務(wù)統(tǒng)計(jì)時(shí)更友好一點(diǎn)。
當(dāng)然了,除了選擇 Spring 和 hutool 的 StopWatch,Apache commons-lang3 的 StopWatch 也是一個(gè)不錯(cuò)的可選項(xiàng),更加靈活多變。
StopWatch sw = StopWatch.createStarted(); Thread.sleep(1000); System.out.printf("耗時(shí):%dms.\n", sw.getTime());
其他兩個(gè)都是通過(guò) new 來(lái)創(chuàng)建 StopWatch 對(duì)象,commons-lang3 還可以通過(guò) createStarted(創(chuàng)建并立即啟動(dòng))、create(創(chuàng)建)來(lái)完成。
還可以調(diào)用 suspend 方法暫停計(jì)時(shí)、resume 方法恢復(fù)計(jì)時(shí)、reset 重新計(jì)時(shí)。
// 暫停計(jì)時(shí) sw.suspend(); System.out.printf("暫停耗時(shí):%dms.\n", sw.getTime()); // 恢復(fù)計(jì)時(shí) sw.resume(); System.out.printf("恢復(fù)耗時(shí):%dms.\n", sw.getTime()); // 停止計(jì)時(shí) sw.stop(); System.out.printf("總耗時(shí):%dms.\n", sw.getTime()); // 重置計(jì)時(shí) sw.reset(); // 開(kāi)始計(jì)時(shí) sw.start(); System.out.printf("重置耗時(shí):%dms.\n", sw.getTime());
ending
文末給自己的編程星球打個(gè)廣告。一個(gè)人可以走得很快,但一群人才能走得更遠(yuǎn)。歡迎加入二哥的編程星球,里面的每個(gè)球友都非常的友善,除了鼓勵(lì)你,還會(huì)給你提出合理的建議。

星球提供的三份專(zhuān)屬專(zhuān)欄《Java 面試指南》、《編程喵 ????(Spring Boot+Vue 前后端分離)實(shí)戰(zhàn)項(xiàng)目筆記》、《Java 版 LeetCode 刷題筆記》,干貨滿(mǎn)滿(mǎn),價(jià)值連城。


已經(jīng)有 480 多名 小伙伴加入二哥的編程星球了,如果你也需要一個(gè)良好的學(xué)習(xí)氛圍,戳鏈接加入我們的大家庭吧!這是一個(gè) Java 學(xué)習(xí)指南 + 編程實(shí)戰(zhàn) + LeetCode 刷題的私密圈子,你可以向二哥提問(wèn)、幫你制定學(xué)習(xí)計(jì)劃、跟著二哥一起做實(shí)戰(zhàn)項(xiàng)目,沖沖沖。

沒(méi)有什么使我停留——除了目的,縱然岸旁有玫瑰、有綠蔭、有寧?kù)o的港灣,我是不系之舟。