Class Stopwatch

java.lang.Object
cloud.opencode.base.core.Stopwatch

public final class Stopwatch extends Object
Stopwatch - A lightweight timing utility for measuring elapsed time 秒表 - 用于测量经过时间的轻量级计时工具

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 Type
    Method
    Description
    static Stopwatch
    Creates and starts a stopwatch 创建并启动秒表
    static Stopwatch
    Creates an unstarted stopwatch 创建未启动的秒表
    Returns the elapsed time as a Duration 返回经过的时间(Duration 格式)
    long
    Returns the elapsed time in the specified time unit 返回指定时间单位的经过时间
    long
    Returns the elapsed time in milliseconds 返回经过的毫秒数
    long
    Returns the elapsed time in nanoseconds 返回经过的纳秒数
    long
    Returns the elapsed time in seconds 返回经过的秒数
    Returns all recorded lap durations as an unmodifiable list.
    boolean
    Returns whether the stopwatch is currently running 返回秒表是否正在运行
    Resets the stopwatch to zero and stops it 重置秒表为零并停止
    Resumes a suspended stopwatch.
    Records a lap (split) time without stopping the stopwatch.
    Starts or resumes the stopwatch 启动或恢复秒表
    Stops the stopwatch 停止秒表
    Suspends the stopwatch without resetting the elapsed time.
    static Duration
    time(Runnable task)
    Times the execution of a runnable and returns the elapsed duration.
    static <T> Pair<T,Duration>
    time(Callable<T> task)
    Times the execution of a callable and returns both the result and elapsed duration.
    Returns a human-readable string representation of the elapsed time 返回人类可读的经过时间字符串

    Methods inherited from class Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
  • Method Details

    • createUnstarted

      public static Stopwatch createUnstarted()
      Creates an unstarted stopwatch 创建未启动的秒表
      Returns:
      a new unstarted stopwatch
    • createStarted

      public static Stopwatch createStarted()
      Creates and starts a stopwatch 创建并启动秒表
      Returns:
      a new started stopwatch
    • time

      public static <T> Pair<T,Duration> time(Callable<T> task) throws Exception
      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

      public static Duration time(Runnable task)
      Times the execution of a runnable and returns the elapsed duration. 计时执行 Runnable 并返回经过的时间。

      Examples | 示例:

      Duration elapsed = Stopwatch.time(() -> heavyComputation());
      
      Parameters:
      task - the runnable to time | 待计时的任务
      Returns:
      the elapsed duration | 经过的时间
    • start

      public Stopwatch start()
      Starts or resumes the stopwatch 启动或恢复秒表
      Returns:
      this stopwatch for fluent chaining
      Throws:
      IllegalStateException - if the stopwatch is already running
    • stop

      public Stopwatch stop()
      Stops the stopwatch 停止秒表
      Returns:
      this stopwatch for fluent chaining
      Throws:
      IllegalStateException - if the stopwatch is not running
    • reset

      public Stopwatch reset()
      Resets the stopwatch to zero and stops it 重置秒表为零并停止
      Returns:
      this stopwatch for fluent chaining
    • suspend

      public Stopwatch 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

      public Stopwatch 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

      public Duration 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

      public List<Duration> getLaps()
      Returns all recorded lap durations as an unmodifiable list. 返回所有已记录的计次时间(不可修改列表)。
      Returns:
      the list of lap durations | 计次时间列表
    • isRunning

      public boolean isRunning()
      Returns whether the stopwatch is currently running 返回秒表是否正在运行
      Returns:
      true if running, false otherwise
    • elapsed

      public Duration elapsed()
      Returns the elapsed time as a Duration 返回经过的时间(Duration 格式)
      Returns:
      the elapsed duration
    • elapsed

      public long elapsed(TimeUnit unit)
      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

      public String 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")
      Overrides:
      toString in class Object
      Returns:
      a formatted string representation