Skip to content

io microsphere util StopWatch

github-actions[bot] edited this page Mar 24, 2026 · 4 revisions

StopWatch

Type: Class | Module: microsphere-java-core | Package: io.microsphere.util | Since: 1.0.0

Source: microsphere-java-core/src/main/java/io/microsphere/util/StopWatch.java

Overview

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.

Declaration

public class StopWatch

Author: Mercy

Version Information

  • Introduced in: 1.0.0
  • Current Project Version: 0.2.2-SNAPSHOT

Version Compatibility

This component is tested and compatible with the following Java versions:

Java Version Status
Java 8 ✅ Compatible
Java 11 ✅ Compatible
Java 17 ✅ Compatible
Java 21 ✅ Compatible
Java 25 ✅ Compatible

Examples

// 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

Method Examples

start

StopWatch stopWatch = new StopWatch("serviceTimer");
StopWatch stopWatch = new StopWatch("myWatch");
  stopWatch.start("databaseQuery");
  // perform the database query
  stopWatch.stop();

start

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();

stop

StopWatch stopWatch = new StopWatch("myWatch");
  stopWatch.start("httpRequest");
  // perform the HTTP request
  stopWatch.stop();
  long elapsed = stopWatch.getTotalTimeNanos();

getCurrentTask

StopWatch stopWatch = new StopWatch("myWatch");
  stopWatch.start("indexing");
  Task current = stopWatch.getCurrentTask();
  System.out.println(current.getTaskName()); // "indexing"

getId

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"
StopWatch stopWatch = new StopWatch("orderService");
  String id = stopWatch.getId(); // "orderService"

getRunningTasks

StopWatch stopWatch = new StopWatch("myWatch");
  stopWatch.start("taskA");
  stopWatch.start("taskB");
  List<Task> running = stopWatch.getRunningTasks();
  System.out.println(running.size()); // 2

getCompletedTasks

StopWatch stopWatch = new StopWatch("myWatch");
  stopWatch.start("init");
  stopWatch.stop();
  List<Task> completed = stopWatch.getCompletedTasks();
  System.out.println(completed.get(0).getTaskName()); // "init"

getTotalTimeNanos

StopWatch stopWatch = new StopWatch("myWatch");
  stopWatch.start("compute");
  stopWatch.stop();
  long nanos = stopWatch.getTotalTimeNanos();
  System.out.println("Total time: " + nanos + " ns");

getTotalTime

StopWatch stopWatch = new StopWatch("myWatch");
  stopWatch.start("fileIO");
  stopWatch.stop();
  long millis = stopWatch.getTotalTime(TimeUnit.MILLISECONDS);
  System.out.println("Total time: " + millis + " ms");

start

StopWatch.Task task = StopWatch.Task.start("parsing");
  // perform parsing work
  task.stop();
  System.out.println(task.getTaskName());    // "parsing"
  System.out.println(task.getElapsedNanos()); // elapsed time in nanoseconds
StopWatch.Task task = StopWatch.Task.start("validation");
  // perform validation
  task.stop();

start

StopWatch.Task task = StopWatch.Task.start("retryableOp", true);
  // perform the operation
  task.stop();
  System.out.println(task.isReentrant()); // true

stop

StopWatch.Task task = StopWatch.Task.start("encoding");
  // perform encoding
  task.stop();
  System.out.println("Elapsed: " + task.getElapsedNanos() + " ns");

getTaskName

StopWatch.Task task = StopWatch.Task.start("sorting");
  String name = task.getTaskName(); // "sorting"

isReentrant

StopWatch.Task task = StopWatch.Task.start("retry", true);
  boolean reentrant = task.isReentrant(); // true

getStartTimeNanos

StopWatch.Task task = StopWatch.Task.start("lookup");
  long startNanos = task.getStartTimeNanos();

getElapsedNanos

StopWatch.Task task = StopWatch.Task.start("render");
  // perform rendering
  task.stop();
  long elapsed = task.getElapsedNanos();
  System.out.println("Render took " + elapsed + " ns");

Usage

Maven Dependency

Add the following dependency to your pom.xml:

<dependency>
    <groupId>io.github.microsphere-projects</groupId>
    <artifactId>microsphere-java-core</artifactId>
    <version>${microsphere-java.version}</version>
</dependency>

Tip: Use the BOM (microsphere-java-dependencies) for consistent version management. See the Getting Started guide.

Import

import io.microsphere.util.StopWatch;

API Reference

Public Methods

Method Description
start Identifier of this StopWatch.
start Starts a new task with the given name and reentrancy control.
stop Stops the most recently started (current) running task, records its elapsed time,
getCurrentTask Returns the most recently started running task without removing it from the running list.
getId Returns the most recently started running task, optionally removing it from the running list.
getRunningTasks Returns an unmodifiable list of tasks that are currently running.
getCompletedTasks Returns an unmodifiable list of tasks that have been completed.
getTotalTimeNanos Returns the total elapsed time of all completed tasks in nanoseconds.
getTotalTime Returns the total elapsed time of all completed tasks, converted to the specified time unit.
start Represents a named task tracked by a StopWatch. Each task records its start time
start Creates and starts a new task with the given name and reentrancy setting.
stop Stops this task and records the elapsed time since it was started.
getTaskName Returns the name of this task.
isReentrant Returns whether this task allows reentrant starts.
getStartTimeNanos Returns the start time of this task in nanoseconds, as reported by System#nanoTime().
getElapsedNanos Returns the elapsed time of this task in nanoseconds.

Method Details

start

public void start(String taskName)

Identifier of this StopWatch.

Handy when we have output from multiple stop watches and need to distinguish between them in log or console output. / private final String id;

/** Running tasks(FIFO) / private final List runningTasks = new LinkedList<>();

/** Completed tasks(FILO) / private final List completedTasks = new LinkedList<>();

/** Total running time. / private long totalTimeNanos;

/** Constructs a new StopWatch with the given identifier.

Example Usage

`StopWatch stopWatch = new StopWatch("serviceTimer");
`

Since: 1.0.0

start

public void start(String taskName, boolean reentrant)

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();
`

Since: 1.0.0

stop

public void stop()

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();
`

Since: 1.0.0

getCurrentTask

public 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"
`

Since: 1.0.0

getId

public String getId()

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"
`

Since: 1.0.0

getRunningTasks

public List<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 running = stopWatch.getRunningTasks();
  System.out.println(running.size()); // 2
`

Since: 1.0.0

getCompletedTasks

public List<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 completed = stopWatch.getCompletedTasks();
  System.out.println(completed.get(0).getTaskName()); // "init"
`

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");
`

Since: 1.0.0

getTotalTime

public long getTotalTime(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");
`

Since: 1.0.0

start

public static Task start(String taskName)

Represents a named task tracked by a StopWatch. Each task records its start time in nanoseconds and calculates the elapsed time when #stop() is called.

Tasks are compared by their taskName only, making task names unique within a single stop watch's running task list.

Example Usage

`StopWatch.Task task = StopWatch.Task.start("parsing");
  // perform parsing work
  task.stop();
  System.out.println(task.getTaskName());    // "parsing"
  System.out.println(task.getElapsedNanos()); // elapsed time in nanoseconds
`

Since: 1.0.0

start

public static Task start(String taskName, boolean reentrant)

Creates and starts a new task with the given name and reentrancy setting.

Example Usage

`StopWatch.Task task = StopWatch.Task.start("retryableOp", true);
  // perform the operation
  task.stop();
  System.out.println(task.isReentrant()); // true
`

Since: 1.0.0

stop

public void stop()

Stops this task and records the elapsed time since it was started.

Example Usage

`StopWatch.Task task = StopWatch.Task.start("encoding");
  // perform encoding
  task.stop();
  System.out.println("Elapsed: " + task.getElapsedNanos() + " ns");
`

Since: 1.0.0

getTaskName

public String getTaskName()

Returns the name of this task.

Example Usage

`StopWatch.Task task = StopWatch.Task.start("sorting");
  String name = task.getTaskName(); // "sorting"
`

Since: 1.0.0

isReentrant

public boolean isReentrant()

Returns whether this task allows reentrant starts.

Example Usage

`StopWatch.Task task = StopWatch.Task.start("retry", true);
  boolean reentrant = task.isReentrant(); // true
`

Since: 1.0.0

getStartTimeNanos

public long getStartTimeNanos()

Returns the start time of this task in nanoseconds, as reported by System#nanoTime().

Example Usage

`StopWatch.Task task = StopWatch.Task.start("lookup");
  long startNanos = task.getStartTimeNanos();
`

Since: 1.0.0

getElapsedNanos

public long getElapsedNanos()

Returns the elapsed time of this task in nanoseconds. This value is zero until #stop() has been called.

Example Usage

`StopWatch.Task task = StopWatch.Task.start("render");
  // perform rendering
  task.stop();
  long elapsed = task.getElapsedNanos();
  System.out.println("Render took " + elapsed + " ns");
`

Since: 1.0.0


This documentation was auto-generated from the source code of microsphere-java.

Home

annotation-processor

java-annotations

java-core

java-test

jdk-tools

lang-model

Clone this wiki locally