首頁 > Java > java教程 > 主體

Spring Boot原始碼如何實現StopWatch優雅統計量耗時

王林
發布: 2023-05-11 14:13:13
轉載
1066 人瀏覽過

引言

昨天,一位球友問我能不能給他解釋一下@SpringBootApplication 註解是什麼意思,還有Spring Boot 的運行原理,於是我就帶著他扒拉了一下這個註解的源碼,還有SpringApplication 類別的run() 方法的源碼,一下子他就明白了。

你別說,看原始碼的過程真的挺有趣,這不,我就發現了一個有趣的點。

public ConfigurableApplicationContext run(String... args) {
	StopWatch stopWatch = new StopWatch();
	stopWatch.start();
	......
	stopWatch.stop();
}
登入後複製

Spring Boot 是用 StopWatch 來統計耗時的,而通常情況下,我們會用 System.currentTimeMillis() 來統計耗時,對吧?程式設計喵????開源專案裡就有這樣一段程式碼,在處理統一日誌處理切面的時候。

@Around("webLog()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    long startTime = System.currentTimeMillis();
    long endTime = System.currentTimeMillis();
    webLog.setSpendTime((int) (endTime - startTime));
}
登入後複製

對比之下,我們就能發現,JDK 提供的 System.currentTimeMillis() 沒有 Spring 提供的 StopWatch 簡潔、清晰。

StopWatch使用

尤其是在多任務的情況下,StopWatch 簡直好用到爆????!

// 创建一个 StopWatch 实例
StopWatch sw = new StopWatch("沉默王二是傻 X");
// 开始计时
sw.start("任务1");
Thread.sleep(1000);
// 停止计时
sw.stop();
System.out.printf("任务1耗时:%d%s.\n", sw.getLastTaskTimeMillis(), "ms");
sw.start("任务2");
Thread.sleep(1100);
sw.stop();
System.out.printf("任务2耗时:%d%s.\n", sw.getLastTaskTimeMillis(), "ms");
System.out.printf("任务数量:%s,总耗时:%ss.\n", sw.getTaskCount(), sw.getTotalTimeSeconds());
登入後複製

看到沒,是不是很簡單?

  • 先new 一個StopWatch 物件

  • #再start 開始計時

  • ##然後stop 停止計時

  • 最後透過sw.getLastTaskTimeMillis() 得出時間差

如果換成System.currentTimeMillis() 就要了老命,先得聲明好幾個long 型的局部變量,然後要第二個減第一個,第三個減第二個,稍微粗心一點(尤其是CV 大法)時,很容易搞錯。

除了可以通過局部時間,還可以透過 sw.getTotalTimeSeconds() 來取得總的耗時。

任務1耗時:1002ms.

任務2耗時:1105ms.
任務數:2,總耗時:2.107820109s.

#另外,StopWatch 還提供了一個sw.prettyPrint() 方法供打印出漂亮的格式化結果:

StopWatch '沉默王二是傻X': running time = 2108529351 ns

- ----------------------------------------------
ns         %     Task name
---------------------------------------------
1004338467  048%  任務1
1104190884  052%  任務2

#有耗時,有佔用百分比,還有任務名,非常清楚。

除了 Spring,hutool 工具庫和 Apache common 工具包都提供了各自的 StopWatch。

Spring Boot原始碼如何實現StopWatch優雅統計量耗時

查看 hutool 工具庫中的 StopWatch 原始碼可以得出,該類別其實就來自 Spring 的 StopWatch.java,用法也完全一致。

Spring Boot原始碼如何實現StopWatch優雅統計量耗時

這表示 hutool 的作者也認為 Spring 的 StopWatch 寫得好,哈哈哈????。

使用Beyond compare比較

使用 Beyond compare 比較後也能得出,兩者除了一個中文註釋,一個英文註釋,代碼幾乎一樣。 setKeepTaskList 方法有比較大的差異。

Spring Boot原始碼如何實現StopWatch優雅統計量耗時

那也就是說,如果你的專案中沒有使用Spring 全家桶,只用了hutool 工具包,那就可以使用hutool 的StopWatch 來取代System.currentTimeMillis ()。

透過分析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;
}
登入後複製

其實可以發現,StopWatch 的內部是透過System.nanoTime() 來計時的,本質上和System.currentTimeMillis() 差異並不大。

nanoTime 比 currentTimeMillis 的粒度更細,前者是以奈秒為單位,後者是以毫秒為單位。

Spring Boot原始碼如何實現StopWatch優雅統計量耗時

注意兩者都是 native 方法,也就是說,值的粒度其實取決於底層的作業系統。

看到這,大家可能會恍然大悟,StopWatch 不過是披著一層外衣的 System.currentTimeMillis() 嘛?

但妙就妙在,這層外衣足夠的漂亮,足夠的優雅。 StopWatch 可以記錄每個子任務的名稱,以及按格式化列印結果,尤其是針對多任務統計時更友善一點。

當然了,除了選擇 Spring 和 hutool 的 StopWatch,Apache commons-lang3 的 StopWatch 也是一個不錯的可選項,更靈活多變。

StopWatch sw = StopWatch.createStarted();
Thread.sleep(1000);
System.out.printf("耗时:%dms.\n", sw.getTime());
登入後複製

其他兩個都是透過 new 來建立 StopWatch 對象,commons-lang3 也可以透過 createStarted(建立並立即啟動)、create(建立)來完成。

還可以呼叫 suspend 方法暫停計時、resume 方法恢復計時、reset 重新計時。

// 暂停计时
sw.suspend();
System.out.printf("暂停耗时:%dms.\n", sw.getTime());
// 恢复计时
sw.resume();
System.out.printf("恢复耗时:%dms.\n", sw.getTime());
// 停止计时
sw.stop();
System.out.printf("总耗时:%dms.\n", sw.getTime());
// 重置计时
sw.reset();
// 开始计时
sw.start();
System.out.printf("重置耗时:%dms.\n", sw.getTime());
登入後複製

以上是Spring Boot原始碼如何實現StopWatch優雅統計量耗時的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:yisu.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!