Class StopWatch


  • public class StopWatch
    extends java.lang.Object

    StopWatch provides a simple way to measure execution time for tasks, supporting nested task tracking. Each task can be started with optional reentrancy control via start(String, boolean).

    By default, tasks are non-reentrant. Attempting to start a non-reentrant task while it's already running will throw an IllegalStateException. If reentrancy is enabled, subsequent calls to start the same task will be ignored until it is stopped.

    Example Usage

    
     // Basic usage
     StopWatch stopWatch = new StopWatch("MyStopWatch");
     stopWatch.start("Task 1");
     // perform operations
     stopWatch.stop();
     System.out.println(stopWatch);  // Outputs: StopWatch[id='MyStopWatch', running tasks=[], completed tasks=[Task[name='Task 1', elapsed(ns)=...]], totalTime(ns)=...]
    
     // Nested tasks
     stopWatch.start("Task A");
     // do something
     stopWatch.start("Task B");
     // do something else
     stopWatch.stop();  // stops Task B
     stopWatch.stop();  // stops Task A
    
     // Reentrant task example
     stopWatch.start("Reentrant Task", true);
     // do something
     stopWatch.start("Reentrant Task", true);  // this call is ignored
     // ...
     stopWatch.stop();  // ends the original task
     

    Note: This class is not thread-safe and should only be used within a single thread.

    Since:
    1.0.0
    Author:
    Mercy
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      static class  StopWatch.Task
      Represents a named task tracked by a StopWatch.
    • Constructor Summary

      Constructors 
      Constructor Description
      StopWatch​(java.lang.String id)
      Constructs a new StopWatch with the given identifier.
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      java.util.List<StopWatch.Task> getCompletedTasks()
      Returns an unmodifiable list of tasks that have been completed.
      StopWatch.Task getCurrentTask()
      Returns the most recently started running task without removing it from the running list.
      protected StopWatch.Task getCurrentTask​(boolean removed)
      Returns the most recently started running task, optionally removing it from the running list.
      java.lang.String getId()
      Returns the identifier of this stop watch.
      java.util.List<StopWatch.Task> getRunningTasks()
      Returns an unmodifiable list of tasks that are currently running.
      long getTotalTime​(java.util.concurrent.TimeUnit timeUnit)
      Returns the total elapsed time of all completed tasks, converted to the specified time unit.
      long getTotalTimeNanos()
      Returns the total elapsed time of all completed tasks in nanoseconds.
      void start​(java.lang.String taskName)
      Starts a new non-reentrant task with the given name.
      void start​(java.lang.String taskName, boolean reentrant)
      Starts a new task with the given name and reentrancy control.
      void stop()
      Stops the most recently started (current) running task, records its elapsed time, and moves it to the completed tasks list.
      java.lang.String toString()
      Returns a string representation of this stop watch, including its identifier, running tasks, completed tasks, and total elapsed time in nanoseconds.
      • Methods inherited from class java.lang.Object

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

      • StopWatch

        public StopWatch​(java.lang.String id)
        Constructs a new StopWatch with the given identifier.

        Example Usage

        
           StopWatch stopWatch = new StopWatch("serviceTimer");
         
        Parameters:
        id - the identifier for this stop watch, used to distinguish output from multiple stop watches
        Since:
        1.0.0
    • Method Detail

      • start

        public void start​(java.lang.String taskName)
                   throws java.lang.IllegalArgumentException,
                          java.lang.IllegalStateException
        Starts a new non-reentrant task with the given name.

        Example Usage

        
           StopWatch stopWatch = new StopWatch("myWatch");
           stopWatch.start("databaseQuery");
           // perform the database query
           stopWatch.stop();
         
        Parameters:
        taskName - the name of the task to start; must not be blank
        Throws:
        java.lang.IllegalArgumentException - if taskName is blank
        java.lang.IllegalStateException - if a non-reentrant task with the same name is already running
        Since:
        1.0.0
      • start

        public void start​(java.lang.String taskName,
                          boolean reentrant)
                   throws java.lang.IllegalArgumentException,
                          java.lang.IllegalStateException
        Starts a new task with the given name and reentrancy control.

        If reentrant is true and a task with the same name is already running, the call is silently ignored. If reentrant is false and the task is already running, an IllegalStateException is thrown.

        Example Usage

        
           StopWatch stopWatch = new StopWatch("myWatch");
           stopWatch.start("cacheRefresh", true);
           // nested call is safely ignored because the task is reentrant
           stopWatch.start("cacheRefresh", true);
           stopWatch.stop();
         
        Parameters:
        taskName - the name of the task to start; must not be blank
        reentrant - true to allow reentrant invocations of the same task name, false to throw an exception on duplicate starts
        Throws:
        java.lang.IllegalArgumentException - if taskName is blank
        java.lang.IllegalStateException - if a non-reentrant task with the same name is already running
        Since:
        1.0.0
      • stop

        public void stop()
                  throws java.lang.IllegalStateException
        Stops the most recently started (current) running task, records its elapsed time, and moves it to the completed tasks list.

        Example Usage

        
           StopWatch stopWatch = new StopWatch("myWatch");
           stopWatch.start("httpRequest");
           // perform the HTTP request
           stopWatch.stop();
           long elapsed = stopWatch.getTotalTimeNanos();
         
        Throws:
        java.lang.IllegalStateException - if no task is currently running
        Since:
        1.0.0
      • getCurrentTask

        public StopWatch.Task getCurrentTask()
        Returns the most recently started running task without removing it from the running list.

        Example Usage

        
           StopWatch stopWatch = new StopWatch("myWatch");
           stopWatch.start("indexing");
           Task current = stopWatch.getCurrentTask();
           System.out.println(current.getTaskName()); // "indexing"
         
        Returns:
        the current running StopWatch.Task, or null if no task is running
        Since:
        1.0.0
      • getCurrentTask

        protected StopWatch.Task getCurrentTask​(boolean removed)
        Returns the most recently started running task, optionally removing it from the running list.

        Example Usage

        
           StopWatch stopWatch = new StopWatch("myWatch");
           stopWatch.start("processing");
           // retrieve and remove the current task from the running list
           Task task = stopWatch.getCurrentTask(true);
           System.out.println(task.getTaskName()); // "processing"
         
        Parameters:
        removed - true to remove the task from the running list, false to only peek
        Returns:
        the current running StopWatch.Task, or null if no task is running
        Since:
        1.0.0
      • getId

        public java.lang.String getId()
        Returns the identifier of this stop watch.

        Example Usage

        
           StopWatch stopWatch = new StopWatch("orderService");
           String id = stopWatch.getId(); // "orderService"
         
        Returns:
        the stop watch identifier
        Since:
        1.0.0
      • getRunningTasks

        public java.util.List<StopWatch.Task> getRunningTasks()
        Returns an unmodifiable list of tasks that are currently running.

        Example Usage

        
           StopWatch stopWatch = new StopWatch("myWatch");
           stopWatch.start("taskA");
           stopWatch.start("taskB");
           List<Task> running = stopWatch.getRunningTasks();
           System.out.println(running.size()); // 2
         
        Returns:
        an unmodifiable list of currently running StopWatch.Task instances
        Since:
        1.0.0
      • getCompletedTasks

        public java.util.List<StopWatch.Task> getCompletedTasks()
        Returns an unmodifiable list of tasks that have been completed.

        Example Usage

        
           StopWatch stopWatch = new StopWatch("myWatch");
           stopWatch.start("init");
           stopWatch.stop();
           List<Task> completed = stopWatch.getCompletedTasks();
           System.out.println(completed.get(0).getTaskName()); // "init"
         
        Returns:
        an unmodifiable list of completed StopWatch.Task instances
        Since:
        1.0.0
      • getTotalTimeNanos

        public long getTotalTimeNanos()
        Returns the total elapsed time of all completed tasks in nanoseconds.

        Example Usage

        
           StopWatch stopWatch = new StopWatch("myWatch");
           stopWatch.start("compute");
           stopWatch.stop();
           long nanos = stopWatch.getTotalTimeNanos();
           System.out.println("Total time: " + nanos + " ns");
         
        Returns:
        the total elapsed time in nanoseconds
        Since:
        1.0.0
      • getTotalTime

        public long getTotalTime​(java.util.concurrent.TimeUnit timeUnit)
        Returns the total elapsed time of all completed tasks, converted to the specified time unit.

        Example Usage

        
           StopWatch stopWatch = new StopWatch("myWatch");
           stopWatch.start("fileIO");
           stopWatch.stop();
           long millis = stopWatch.getTotalTime(TimeUnit.MILLISECONDS);
           System.out.println("Total time: " + millis + " ms");
         
        Parameters:
        timeUnit - the desired time unit for the result
        Returns:
        the total elapsed time in the specified time unit
        Since:
        1.0.0
      • toString

        public java.lang.String toString()
        Returns a string representation of this stop watch, including its identifier, running tasks, completed tasks, and total elapsed time in nanoseconds.

        Example Usage

        
           StopWatch stopWatch = new StopWatch("myWatch");
           stopWatch.start("task1");
           stopWatch.stop();
           System.out.println(stopWatch.toString());
           // StopWatch[id='myWatch', running tasks=[], completed tasks=[Task[name='task1', elapsed(ns)=...]], totalTime(ns)=...]
         
        Overrides:
        toString in class java.lang.Object
        Returns:
        a descriptive string representation of this stop watch
        Since:
        1.0.0