Java 生態中有三個主流 StopWatch 實現,API 設計差異較大。本文通過實測代碼對比 Spring、Guava、Commons-Lang 三者用法,推薦最佳選擇。
| 庫 | 類全路徑 | 特點 | 推薦指數 |
|---|---|---|---|
| Spring | org.springframework.util.StopWatch | 任務分組、統計報告豐富、線程不安全 | ⭐⭐⭐⭐⭐ |
| Guava | com.google.common.base.Stopwatch | 不可變、線程安全、納秒精度、流式 API | ⭐⭐⭐⭐ |
| Commons-Lang | org.apache.commons.lang3.time.StopWatch | 可繼承、支持暫停/恢復、分割計時 | ⭐⭐⭐ |
import org.springframework.util.StopWatch;
public class PerfTest {
public static void main(String[] args) {
StopWatch sw = new StopWatch("DB操作性能測試");
sw.start("查詢用戶");
userDao.findAll();
sw.stop();
sw.start("插入訂單");
orderDao.insert(order);
sw.stop();
sw.start("發送郵件");
mailService.send();
sw.stop();
// 多種輸出格式
System.out.println(sw.prettyPrint()); // 格式化表格
System.out.println(sw.shortSummary()); // 簡短摘要
System.out.println("總耗時: " + sw.getTotalTimeMillis() + "ms");
System.out.println("任務數: " + sw.getTaskCount());
}
}
輸出示例:
StopWatch 'DB操作性能測試': running time (millis) = 411
-----------------------------------------
ms % Task name
-----------------------------------------
00011 003% 查詢用戶
00400 097% 插入訂單
00000 000% 發送郵件
Short summary: 411 ms
import com.google.common.base.Stopwatch;
import java.util.concurrent.TimeUnit;
Stopwatch sw = Stopwatch.createStarted();
// ... 業務代碼 ...
sw.stop();
System.out.println("耗時: " + sw.elapsed(TimeUnit.MILLISECONDS) + " ms");
// 或
System.out.println(sw); // 輸出: 123.4 ms
import org.apache.commons.lang3.time.StopWatch;
StopWatch sw = new StopWatch();
sw.start();
// ...
sw.split(); // 分割點
// ...
sw.stop();
org.springframework.util.StopWatch,無額外依賴,報告最豐富Stopwatch 線程安全、不可變,適合並發環境System.nanoTime() 而非 currentTimeMillis()Spring StopWatch 以豐富的統計報告、零依賴(Spring 項目)、直觀 API 成為日常性能排查首選。理解三者差異,按場景選型,事半功倍。