Class StopWatch

java.lang.Object
cloud.opencode.base.date.StopWatch

public class StopWatch extends Object
High-precision StopWatch for performance timing 高精度计时器,用于性能计时

This class provides a simple way to time code execution with support for multiple laps, task naming, and formatted output. It uses System.nanoTime() for high precision.

此类提供一种简单的方式来计时代码执行,支持多圈、任务命名和格式化输出。 使用System.nanoTime()以获得高精度。

Features | 主要功能:

  • High-precision timing using nanoTime - 使用nanoTime高精度计时
  • Multiple named tasks/laps - 多个命名任务/圈
  • Formatted output - 格式化输出
  • Thread-safe for single-threaded use - 单线程使用时线程安全

Usage Examples | 使用示例:

// Simple timing
StopWatch sw = StopWatch.start();
// ... do something
Duration elapsed = sw.stop();
System.out.println("Elapsed: " + sw.formatTime());

// Named tasks
StopWatch sw = new StopWatch("My Process");
sw.start("Task 1");
// ... task 1
sw.stop();
sw.start("Task 2");
// ... task 2
sw.stop();
System.out.println(sw.prettyPrint());

// Quick timing with lambda
Duration elapsed = StopWatch.time(() -> {
    // ... operation
});

Performance | 性能特性:

  • Nanosecond precision - 纳秒精度
  • Minimal overhead - 最小开销

Security | 安全性:

  • Not thread-safe for concurrent access - 不支持并发访问
  • Thread-safe for single-threaded use - 单线程使用时线程安全
Since:
JDK 25, opencode-base-date V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Nested Class Summary

    Nested Classes
    Modifier and Type
    Class
    Description
    static final record 
    Information about a timed task 计时任务的信息
  • Constructor Summary

    Constructors
    Constructor
    Description
    Creates a StopWatch with no name 创建无名称的StopWatch
    Creates a StopWatch with the specified name 创建具有指定名称的StopWatch
  • Method Summary

    Modifier and Type
    Method
    Description
    static StopWatch
    Creates and starts a StopWatch 创建并启动StopWatch
    static StopWatch
    Creates and starts a named StopWatch 创建并启动命名的StopWatch
    Formats the total time as a human-readable string 将总时间格式化为人类可读的字符串
    long
    Gets the current elapsed time in nanoseconds (if running) 获取当前经过时间(纳秒,如果正在运行)
    Gets the name of this stopwatch 获取计时器的名称
    int
    Gets the number of completed tasks 获取已完成任务的数量
    Gets the list of completed tasks 获取已完成任务的列表
    Gets the total elapsed time as Duration 获取总经过时间作为Duration
    long
    Gets the total elapsed time in milliseconds 获取总经过时间(毫秒)
    long
    Gets the total elapsed time in nanoseconds 获取总经过时间(纳秒)
    double
    Gets the total elapsed time in seconds 获取总经过时间(秒)
    boolean
    Checks if the stopwatch is currently running 检查计时器是否正在运行
    Creates a pretty-printed summary of all tasks 创建所有任务的漂亮打印摘要
    void
    Resets the stopwatch 重置计时器
    Creates a short summary string 创建简短的摘要字符串
    split(String newTaskName)
    Splits the current lap and starts a new one 分割当前圈并开始新的一圈
    void
    start(String taskName)
    Starts timing a new task 开始计时新任务
    Stops timing the current task 停止计时当前任务
    static Duration
    time(Runnable runnable)
    Times the execution of a Runnable 计时Runnable的执行
    static Duration
    time(String taskName, Runnable runnable)
    Times the execution of a Runnable with a task name 使用任务名称计时Runnable的执行
     

    Methods inherited from class Object

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

    • StopWatch

      public StopWatch()
      Creates a StopWatch with no name 创建无名称的StopWatch
    • StopWatch

      public StopWatch(String name)
      Creates a StopWatch with the specified name 创建具有指定名称的StopWatch
      Parameters:
      name - the name | 名称
  • Method Details

    • createStarted

      public static StopWatch createStarted()
      Creates and starts a StopWatch 创建并启动StopWatch
      Returns:
      the started StopWatch | 已启动的StopWatch
    • createStarted

      public static StopWatch createStarted(String name)
      Creates and starts a named StopWatch 创建并启动命名的StopWatch
      Parameters:
      name - the name | 名称
      Returns:
      the started StopWatch | 已启动的StopWatch
    • time

      public static Duration time(Runnable runnable)
      Times the execution of a Runnable 计时Runnable的执行
      Parameters:
      runnable - the runnable to time | 要计时的Runnable
      Returns:
      the elapsed duration | 经过的时长
    • time

      public static Duration time(String taskName, Runnable runnable)
      Times the execution of a Runnable with a task name 使用任务名称计时Runnable的执行
      Parameters:
      taskName - the task name | 任务名称
      runnable - the runnable to time | 要计时的Runnable
      Returns:
      the elapsed duration | 经过的时长
    • start

      public void start(String taskName)
      Starts timing a new task 开始计时新任务
      Parameters:
      taskName - the task name | 任务名称
      Throws:
      IllegalStateException - if already running | 如果已在运行则抛出异常
    • stop

      public Duration stop()
      Stops timing the current task 停止计时当前任务
      Returns:
      the elapsed duration | 经过的时长
      Throws:
      IllegalStateException - if not running | 如果未运行则抛出异常
    • reset

      public void reset()
      Resets the stopwatch 重置计时器
    • split

      public Duration split(String newTaskName)
      Splits the current lap and starts a new one 分割当前圈并开始新的一圈
      Parameters:
      newTaskName - the name for the new task | 新任务的名称
      Returns:
      the elapsed duration of the previous task | 上一个任务的经过时长
    • isRunning

      public boolean isRunning()
      Checks if the stopwatch is currently running 检查计时器是否正在运行
      Returns:
      true if running | 如果正在运行返回true
    • getName

      public String getName()
      Gets the name of this stopwatch 获取计时器的名称
      Returns:
      the name | 名称
    • getTaskCount

      public int getTaskCount()
      Gets the number of completed tasks 获取已完成任务的数量
      Returns:
      the task count | 任务数量
    • getTasks

      public List<StopWatch.TaskInfo> getTasks()
      Gets the list of completed tasks 获取已完成任务的列表
      Returns:
      the task list | 任务列表
    • getTotalTimeNanos

      public long getTotalTimeNanos()
      Gets the total elapsed time in nanoseconds 获取总经过时间(纳秒)
      Returns:
      the total time in nanos | 总纳秒时间
    • getTotalTimeMillis

      public long getTotalTimeMillis()
      Gets the total elapsed time in milliseconds 获取总经过时间(毫秒)
      Returns:
      the total time in millis | 总毫秒时间
    • getTotalTimeSeconds

      public double getTotalTimeSeconds()
      Gets the total elapsed time in seconds 获取总经过时间(秒)
      Returns:
      the total time in seconds | 总秒时间
    • getTotalDuration

      public Duration getTotalDuration()
      Gets the total elapsed time as Duration 获取总经过时间作为Duration
      Returns:
      the total Duration | 总Duration
    • getCurrentTimeNanos

      public long getCurrentTimeNanos()
      Gets the current elapsed time in nanoseconds (if running) 获取当前经过时间(纳秒,如果正在运行)
      Returns:
      the current elapsed time, or total time if stopped | 当前经过时间,如果已停止则返回总时间
    • formatTime

      public String formatTime()
      Formats the total time as a human-readable string 将总时间格式化为人类可读的字符串
      Returns:
      the formatted time | 格式化的时间
    • prettyPrint

      public String prettyPrint()
      Creates a pretty-printed summary of all tasks 创建所有任务的漂亮打印摘要
      Returns:
      the summary string | 摘要字符串
    • shortSummary

      public String shortSummary()
      Creates a short summary string 创建简短的摘要字符串
      Returns:
      the short summary | 简短摘要
    • toString

      public String toString()
      Overrides:
      toString in class Object