Class StopWatch
java.lang.Object
cloud.opencode.base.log.perf.StopWatch
- All Implemented Interfaces:
AutoCloseable
StopWatch - High-precision Timer for Performance Measurement
计时器 - 用于性能测量的高精度计时器
StopWatch provides a simple way to measure elapsed time for operations. It uses System.nanoTime() for high precision timing.
StopWatch 提供了一种测量操作耗时的简单方法。它使用 System.nanoTime() 进行高精度计时。
Example | 示例:
// Basic usage
StopWatch watch = StopWatch.start("queryUsers");
List<User> users = userDao.findAll();
watch.stopAndLog(); // Output: queryUsers completed in 123ms
// With try-with-resources
try (StopWatch watch = StopWatch.start("processOrder")) {
orderService.process(order);
} // Automatically logs on close
// Manual control
StopWatch watch = StopWatch.create("batchProcess");
watch.startTiming();
// ... operations
long elapsed = watch.stop().getElapsedMillis();
Features | 主要功能:
- High-precision timing via System.nanoTime() - 通过 System.nanoTime() 的高精度计时
- AutoCloseable for try-with-resources - 支持 try-with-resources 的 AutoCloseable
- Automatic logging with optional threshold warning - 自动记录,可选阈值警告
- Manual start/stop/reset control - 手动启动/停止/重置控制
Security | 安全性:
- Thread-safe: No (not designed for shared use) - 线程安全: 否(不适用于共享使用)
- Null-safe: No (operation name must not be null) - 空值安全: 否(操作名称不能为 null)
- Since:
- JDK 25, opencode-base-log V1.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionvoidclose()static StopWatchCreates a StopWatch without starting it.Returns the elapsed time as a Duration.longReturns the elapsed time in milliseconds.longReturns the elapsed time in nanoseconds.Returns the operation name.booleanChecks if the timer is running.reset()Resets the timer.static StopWatchCreates and starts a new StopWatch.Starts the timer.stop()Stops the timer.voidStops the timer and logs the result.voidstopAndLog(long thresholdMs) Stops the timer and logs with threshold warning.toString()
-
Method Details
-
start
-
create
-
startTiming
-
stop
-
reset
-
getElapsedMillis
public long getElapsedMillis()Returns the elapsed time in milliseconds. 返回以毫秒为单位的耗时。- Returns:
- elapsed time in milliseconds - 毫秒耗时
-
getElapsedNanos
public long getElapsedNanos()Returns the elapsed time in nanoseconds. 返回以纳秒为单位的耗时。- Returns:
- elapsed time in nanoseconds - 纳秒耗时
-
getElapsed
Returns the elapsed time as a Duration. 返回耗时作为 Duration。- Returns:
- the elapsed Duration - 耗时 Duration
-
isRunning
public boolean isRunning()Checks if the timer is running. 检查计时器是否正在运行。- Returns:
- true if running - 如果运行中返回 true
-
getOperation
-
stopAndLog
public void stopAndLog()Stops the timer and logs the result. 停止计时器并记录结果。 -
stopAndLog
public void stopAndLog(long thresholdMs) Stops the timer and logs with threshold warning. 停止计时器并带阈值警告记录。- Parameters:
thresholdMs- the threshold in milliseconds - 毫秒阈值
-
close
public void close()- Specified by:
closein interfaceAutoCloseable
-
toString
-