Class Stopwatch
This class provides a simple and efficient way to measure elapsed time, commonly used for performance testing and debugging.
该类提供了一种简单高效的方式来测量经过的时间,通常用于性能测试和调试。
Features | 主要功能:
- High-precision timing using System.nanoTime() - 使用 System.nanoTime() 实现高精度计时
- Start, stop, reset, and resume operations - 支持开始、停止、重置和恢复操作
- Multiple time unit conversions - 多种时间单位转换
- Fluent API design - 流式 API 设计
- Suspend and resume without reset (suspend, resume) - 暂停和恢复(不重置)
- Lap/split timing (split, getLaps) - 计次/分段计时
- One-liner timing (time) - 一行代码计时
Usage Examples | 使用示例:
// Basic usage | 基本用法
Stopwatch sw = Stopwatch.createStarted();
// ... do something
long elapsedMs = sw.elapsed(TimeUnit.MILLISECONDS);
System.out.println("Elapsed: " + sw); // "Elapsed: 123.4 ms"
// Manual control | 手动控制
Stopwatch sw = Stopwatch.createUnstarted();
sw.start();
// ... do something
sw.stop();
Duration duration = sw.elapsed();
// Fluent style | 流式风格
Stopwatch.createStarted()
.stop()
.reset()
.start();
// Suspend/Resume | 暂停/恢复
sw.suspend();
// ... pause ...
sw.resume();
// Lap timing | 计次
Stopwatch sw = Stopwatch.createStarted();
// ... phase 1 ...
Duration lap1 = sw.split();
// ... phase 2 ...
Duration lap2 = sw.split();
List<Duration> laps = sw.getLaps(); // [lap1, lap2]
// One-liner timing | 一行代码计时
Duration elapsed = Stopwatch.time(() -> heavyComputation());
var timed = Stopwatch.time(() -> fetchData()); // Pair<Result, Duration>
Thread Safety | 线程安全:
This class is NOT thread-safe. For concurrent timing, use external synchronization.
此类非线程安全。如需并发计时,请使用外部同步。
- Since:
- JDK 25, opencode-base-core V1.0.0
- Author:
- Leon Soo www.LeonSoo.com
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionstatic StopwatchCreates and starts a stopwatch 创建并启动秒表static StopwatchCreates an unstarted stopwatch 创建未启动的秒表elapsed()Returns the elapsed time as a Duration 返回经过的时间(Duration 格式)longReturns the elapsed time in the specified time unit 返回指定时间单位的经过时间longReturns the elapsed time in milliseconds 返回经过的毫秒数longReturns the elapsed time in nanoseconds 返回经过的纳秒数longReturns the elapsed time in seconds 返回经过的秒数getLaps()Returns all recorded lap durations as an unmodifiable list.booleanReturns whether the stopwatch is currently running 返回秒表是否正在运行reset()Resets the stopwatch to zero and stops it 重置秒表为零并停止resume()Resumes a suspended stopwatch.split()Records a lap (split) time without stopping the stopwatch.start()Starts or resumes the stopwatch 启动或恢复秒表stop()Stops the stopwatch 停止秒表suspend()Suspends the stopwatch without resetting the elapsed time.static DurationTimes the execution of a runnable and returns the elapsed duration.Times the execution of a callable and returns both the result and elapsed duration.toString()Returns a human-readable string representation of the elapsed time 返回人类可读的经过时间字符串
-
Method Details
-
createUnstarted
Creates an unstarted stopwatch 创建未启动的秒表- Returns:
- a new unstarted stopwatch
-
createStarted
Creates and starts a stopwatch 创建并启动秒表- Returns:
- a new started stopwatch
-
time
Times the execution of a callable and returns both the result and elapsed duration. 计时执行 Callable 并返回结果和经过的时间。Examples | 示例:
var timed = Stopwatch.time(() -> fetchData()); System.out.println("Result: " + timed.left() + ", took " + timed.right());- Type Parameters:
T- the result type | 结果类型- Parameters:
task- the callable to time | 待计时的任务- Returns:
- a Pair of (result, elapsed duration) | (结果, 经过时间) 的 Pair
- Throws:
Exception- if the callable throws | 如果任务抛出异常
-
time
-
start
Starts or resumes the stopwatch 启动或恢复秒表- Returns:
- this stopwatch for fluent chaining
- Throws:
IllegalStateException- if the stopwatch is already running
-
stop
Stops the stopwatch 停止秒表- Returns:
- this stopwatch for fluent chaining
- Throws:
IllegalStateException- if the stopwatch is not running
-
reset
Resets the stopwatch to zero and stops it 重置秒表为零并停止- Returns:
- this stopwatch for fluent chaining
-
suspend
Suspends the stopwatch without resetting the elapsed time. 暂停秒表但不重置已经过的时间。The stopwatch can be resumed later with
resume(). The elapsed time between suspend and resume is not counted.稍后可以通过
resume()恢复。暂停和恢复之间的时间不计入。- Returns:
- this stopwatch for fluent chaining | 此秒表,支持链式调用
- Throws:
IllegalStateException- if the stopwatch is not running | 如果秒表未运行
-
resume
Resumes a suspended stopwatch. 恢复已暂停的秒表。Equivalent to calling
start()on a stopped (but not reset) stopwatch.等同于在已停止(但未重置)的秒表上调用
start()。- Returns:
- this stopwatch for fluent chaining | 此秒表,支持链式调用
- Throws:
IllegalStateException- if the stopwatch is already running | 如果秒表已在运行
-
split
Records a lap (split) time without stopping the stopwatch. 记录一个计次(分段)时间,不停止秒表。Returns the duration since the last split (or since start if no previous split). The stopwatch continues running.
返回自上次分段以来的时间(如果没有上次分段,则返回自启动以来的时间)。 秒表继续运行。
- Returns:
- the lap duration | 本次计次的时间
- Throws:
IllegalStateException- if the stopwatch is not running | 如果秒表未运行
-
getLaps
-
isRunning
public boolean isRunning()Returns whether the stopwatch is currently running 返回秒表是否正在运行- Returns:
- true if running, false otherwise
-
elapsed
Returns the elapsed time as a Duration 返回经过的时间(Duration 格式)- Returns:
- the elapsed duration
-
elapsed
Returns the elapsed time in the specified time unit 返回指定时间单位的经过时间- Parameters:
unit- the desired time unit- Returns:
- the elapsed time in the specified unit
-
elapsedNanos
public long elapsedNanos()Returns the elapsed time in nanoseconds 返回经过的纳秒数- Returns:
- elapsed nanoseconds
-
elapsedMillis
public long elapsedMillis()Returns the elapsed time in milliseconds 返回经过的毫秒数- Returns:
- elapsed milliseconds
-
elapsedSeconds
public long elapsedSeconds()Returns the elapsed time in seconds 返回经过的秒数- Returns:
- elapsed seconds
-
toString
Returns a human-readable string representation of the elapsed time 返回人类可读的经过时间字符串The time unit is automatically selected based on the magnitude:
- Less than 1 microsecond: nanoseconds (e.g., "123 ns")
- Less than 1 millisecond: microseconds (e.g., "123.4 μs")
- Less than 1 second: milliseconds (e.g., "123.4 ms")
- Less than 1 minute: seconds (e.g., "12.34 s")
- Otherwise: minutes (e.g., "1.23 min")
-