-
Notifications
You must be signed in to change notification settings - Fork 53
io microsphere util 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
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.
`// 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.
public class StopWatchAuthor: Mercy
-
Introduced in:
1.0.0 -
Current Project Version:
0.2.2-SNAPSHOT
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 |
// 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 taskStopWatch stopWatch = new StopWatch("serviceTimer");StopWatch stopWatch = new StopWatch("myWatch");
stopWatch.start("databaseQuery");
// perform the database query
stopWatch.stop();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();StopWatch stopWatch = new StopWatch("myWatch");
stopWatch.start("httpRequest");
// perform the HTTP request
stopWatch.stop();
long elapsed = stopWatch.getTotalTimeNanos();StopWatch stopWatch = new StopWatch("myWatch");
stopWatch.start("indexing");
Task current = stopWatch.getCurrentTask();
System.out.println(current.getTaskName()); // "indexing"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"StopWatch stopWatch = new StopWatch("myWatch");
stopWatch.start("taskA");
stopWatch.start("taskB");
List<Task> running = stopWatch.getRunningTasks();
System.out.println(running.size()); // 2StopWatch stopWatch = new StopWatch("myWatch");
stopWatch.start("init");
stopWatch.stop();
List<Task> completed = stopWatch.getCompletedTasks();
System.out.println(completed.get(0).getTaskName()); // "init"StopWatch stopWatch = new StopWatch("myWatch");
stopWatch.start("compute");
stopWatch.stop();
long nanos = stopWatch.getTotalTimeNanos();
System.out.println("Total time: " + nanos + " ns");StopWatch stopWatch = new StopWatch("myWatch");
stopWatch.start("fileIO");
stopWatch.stop();
long millis = stopWatch.getTotalTime(TimeUnit.MILLISECONDS);
System.out.println("Total time: " + millis + " ms");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 nanosecondsStopWatch.Task task = StopWatch.Task.start("validation");
// perform validation
task.stop();StopWatch.Task task = StopWatch.Task.start("retryableOp", true);
// perform the operation
task.stop();
System.out.println(task.isReentrant()); // trueStopWatch.Task task = StopWatch.Task.start("encoding");
// perform encoding
task.stop();
System.out.println("Elapsed: " + task.getElapsedNanos() + " ns");StopWatch.Task task = StopWatch.Task.start("sorting");
String name = task.getTaskName(); // "sorting"StopWatch.Task task = StopWatch.Task.start("retry", true);
boolean reentrant = task.isReentrant(); // trueStopWatch.Task task = StopWatch.Task.start("lookup");
long startNanos = task.getStartTimeNanos();StopWatch.Task task = StopWatch.Task.start("render");
// perform rendering
task.stop();
long elapsed = task.getElapsedNanos();
System.out.println("Render took " + elapsed + " ns");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 io.microsphere.util.StopWatch;| 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. |
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.
`StopWatch stopWatch = new StopWatch("serviceTimer");
`
Since: 1.0.0
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.
`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
public void stop()Stops the most recently started (current) running task, records its elapsed time, and moves it to the completed tasks list.
`StopWatch stopWatch = new StopWatch("myWatch");
stopWatch.start("httpRequest");
// perform the HTTP request
stopWatch.stop();
long elapsed = stopWatch.getTotalTimeNanos();
`
Since: 1.0.0
public Task getCurrentTask()Returns the most recently started running task without removing it from the running list.
`StopWatch stopWatch = new StopWatch("myWatch");
stopWatch.start("indexing");
Task current = stopWatch.getCurrentTask();
System.out.println(current.getTaskName()); // "indexing"
`
Since: 1.0.0
public String getId()Returns the most recently started running task, optionally removing it from the running list.
`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
public List<Task> getRunningTasks()Returns an unmodifiable list of tasks that are currently running.
`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
public List<Task> getCompletedTasks()Returns an unmodifiable list of tasks that have been completed.
`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
public long getTotalTimeNanos()Returns the total elapsed time of all completed tasks in nanoseconds.
`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
public long getTotalTime(TimeUnit timeUnit)Returns the total elapsed time of all completed tasks, converted to the specified time unit.
`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
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.
`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
public static Task start(String taskName, boolean reentrant)Creates and starts a new task with the given name and reentrancy setting.
`StopWatch.Task task = StopWatch.Task.start("retryableOp", true);
// perform the operation
task.stop();
System.out.println(task.isReentrant()); // true
`
Since: 1.0.0
public void stop()Stops this task and records the elapsed time since it was started.
`StopWatch.Task task = StopWatch.Task.start("encoding");
// perform encoding
task.stop();
System.out.println("Elapsed: " + task.getElapsedNanos() + " ns");
`
Since: 1.0.0
public String getTaskName()Returns the name of this task.
`StopWatch.Task task = StopWatch.Task.start("sorting");
String name = task.getTaskName(); // "sorting"
`
Since: 1.0.0
public boolean isReentrant()Returns whether this task allows reentrant starts.
`StopWatch.Task task = StopWatch.Task.start("retry", true);
boolean reentrant = task.isReentrant(); // true
`
Since: 1.0.0
public long getStartTimeNanos()Returns the start time of this task in nanoseconds, as reported by System#nanoTime().
`StopWatch.Task task = StopWatch.Task.start("lookup");
long startNanos = task.getStartTimeNanos();
`
Since: 1.0.0
public long getElapsedNanos()Returns the elapsed time of this task in nanoseconds.
This value is zero until #stop() has been called.
`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.
annotation-processor
- ConfigurationPropertyAnnotationProcessor
- ConfigurationPropertyJSONElementVisitor
- FilerProcessor
- ResourceProcessor
java-annotations
java-core
- ACLLoggerFactory
- AbstractArtifactResourceResolver
- AbstractConverter
- AbstractDeque
- AbstractEventDispatcher
- AbstractLogger
- AbstractURLClassPathHandle
- AccessibleObjectUtils
- AdditionalMetadataResourceConfigurationPropertyLoader
- AnnotationUtils
- ArchiveFileArtifactResourceResolver
- ArrayEnumeration
- ArrayStack
- ArrayUtils
- Artifact
- ArtifactDetector
- ArtifactResourceResolver
- Assert
- BannedArtifactClassLoadingExecutor
- BaseUtils
- BeanMetadata
- BeanProperty
- BeanUtils
- ByteArrayToObjectConverter
- CharSequenceComparator
- CharSequenceUtils
- CharsetUtils
- ClassDataRepository
- ClassDefinition
- ClassFileJarEntryFilter
- ClassFilter
- ClassLoaderUtils
- ClassPathResourceConfigurationPropertyLoader
- ClassPathUtils
- ClassUtils
- ClassicProcessIdResolver
- ClassicURLClassPathHandle
- CollectionUtils
- Compatible
- CompositeSubProtocolURLConnectionFactory
- CompositeURLStreamHandlerFactory
- ConditionalEventListener
- ConfigurationProperty
- ConfigurationPropertyGenerator
- ConfigurationPropertyLoader
- ConfigurationPropertyReader
- Configurer
- ConsoleURLConnection
- Constants
- ConstructorDefinition
- ConstructorUtils
- Converter
- Converters
- CustomizedThreadFactory
- DefaultConfigurationPropertyGenerator
- DefaultConfigurationPropertyReader
- DefaultDeserializer
- DefaultEntry
- DefaultSerializer
- DelegatingBlockingQueue
- DelegatingDeque
- DelegatingIterator
- DelegatingQueue
- DelegatingScheduledExecutorService
- DelegatingURLConnection
- DelegatingURLStreamHandlerFactory
- DelegatingWrapper
- Deprecation
- Deserializer
- Deserializers
- DirectEventDispatcher
- DirectoryFileFilter
- EmptyDeque
- EmptyIterable
- EmptyIterator
- EnumerationIteratorAdapter
- EnumerationUtils
- Event
- EventDispatcher
- EventListener
- ExceptionUtils
- ExecutableDefinition
- ExecutableUtils
- ExecutorUtils
- ExtendableProtocolURLStreamHandler
- FastByteArrayInputStream
- FastByteArrayOutputStream
- FieldDefinition
- FieldUtils
- FileChangedEvent
- FileChangedListener
- FileConstants
- FileExtensionFilter
- FileUtils
- FileWatchService
- Filter
- FilterOperator
- FilterUtils
- FormatUtils
- Functional
- GenericEvent
- GenericEventListener
- Handler
- Handler
- HierarchicalClassComparator
- IOFileFilter
- IOUtils
- ImmutableEntry
- IterableAdapter
- IterableUtils
- Iterators
- JDKLoggerFactory
- JSON
- JSONArray
- JSONException
- JSONObject
- JSONStringer
- JSONTokener
- JSONUtils
- JarEntryFilter
- JarUtils
- JavaType
- JmxUtils
- ListUtils
- Listenable
- Lists
- Logger
- LoggerFactory
- LoggingFileChangedListener
- MBeanAttribute
- MBeanAttributeInfoBuilder
- MBeanConstructorInfoBuilder
- MBeanDescribableBuilder
- MBeanExecutableInfoBuilder
- MBeanFeatureInfoBuilder
- MBeanInfoBuilder
- MBeanNotificationInfoBuilder
- MBeanOperationInfoBuilder
- MBeanParameterInfoBuilder
- ManagementUtils
- ManifestArtifactResourceResolver
- MapToPropertiesConverter
- MapUtils
- Maps
- MavenArtifact
- MavenArtifactResourceResolver
- MemberDefinition
- MemberUtils
- MetadataResourceConfigurationPropertyLoader
- MethodDefinition
- MethodHandleUtils
- MethodHandlesLookupUtils
- MethodUtils
- ModernProcessIdResolver
- ModernURLClassPathHandle
- Modifier
- MultiValueConverter
- MultipleType
- MutableInteger
- MutableURLStreamHandlerFactory
- NameFileFilter
- NoOpLogger
- NoOpLoggerFactory
- NoOpURLClassPathHandle
- NumberToByteConverter
- NumberToCharacterConverter
- NumberToDoubleConverter
- NumberToFloatConverter
- NumberToIntegerConverter
- NumberToLongConverter
- NumberToShortConverter
- NumberUtils
- ObjectToBooleanConverter
- ObjectToByteArrayConverter
- ObjectToByteConverter
- ObjectToCharacterConverter
- ObjectToDoubleConverter
- ObjectToFloatConverter
- ObjectToIntegerConverter
- ObjectToLongConverter
- ObjectToOptionalConverter
- ObjectToShortConverter
- ObjectToStringConverter
- PackageNameClassFilter
- PackageNameClassNameFilter
- ParallelEventDispatcher
- ParameterizedTypeImpl
- PathConstants
- Predicates
- Prioritized
- PriorityComparator
- ProcessExecutor
- ProcessIdResolver
- ProcessManager
- PropertiesToStringConverter
- PropertiesUtils
- PropertyConstants
- PropertyResourceBundleControl
- PropertyResourceBundleUtils
- ProtocolConstants
- ProxyUtils
- QueueUtils
- ReadOnlyIterator
- ReflectionUtils
- ReflectiveConfigurationPropertyGenerator
- ReflectiveDefinition
- ResourceConstants
- ReversedDeque
- Scanner
- SecurityUtils
- SeparatorConstants
- Serializer
- Serializers
- ServiceLoaderURLStreamHandlerFactory
- ServiceLoaderUtils
- ServiceLoadingURLClassPathHandle
- SetUtils
- Sets
- Sfl4jLoggerFactory
- ShutdownHookCallbacksThread
- ShutdownHookUtils
- SimpleClassScanner
- SimpleFileScanner
- SimpleJarEntryScanner
- SingletonDeque
- SingletonEnumeration
- SingletonIterator
- StackTraceUtils
- StandardFileWatchService
- StandardURLStreamHandlerFactory
- StopWatch
- StreamArtifactResourceResolver
- Streams
- StringBuilderWriter
- StringConverter
- StringDeserializer
- StringSerializer
- StringToArrayConverter
- StringToBlockingDequeConverter
- StringToBlockingQueueConverter
- StringToBooleanConverter
- StringToByteConverter
- StringToCharArrayConverter
- StringToCharacterConverter
- StringToClassConverter
- StringToCollectionConverter
- StringToDequeConverter
- StringToDoubleConverter
- StringToDurationConverter
- StringToFloatConverter
- StringToInputStreamConverter
- StringToIntegerConverter
- StringToIterableConverter
- StringToListConverter
- StringToLongConverter
- StringToMultiValueConverter
- StringToNavigableSetConverter
- StringToQueueConverter
- StringToSetConverter
- StringToShortConverter
- StringToSortedSetConverter
- StringToStringConverter
- StringToTransferQueueConverter
- StringUtils
- SubProtocolURLConnectionFactory
- SymbolConstants
- SystemUtils
- ThrowableAction
- ThrowableBiConsumer
- ThrowableBiFunction
- ThrowableConsumer
- ThrowableFunction
- ThrowableSupplier
- ThrowableUtils
- TrueClassFilter
- TrueFileFilter
- TypeArgument
- TypeFinder
- TypeUtils
- URLClassPathHandle
- URLUtils
- UnmodifiableDeque
- UnmodifiableIterator
- UnmodifiableQueue
- Utils
- ValueHolder
- Version
- VersionUtils
- VirtualMachineProcessIdResolver
- Wrapper
- WrapperProcessor
java-test
- AbstractAnnotationProcessingTest
- Ancestor
- AnnotationProcessingTestProcessor
- ArrayTypeModel
- CollectionTypeModel
- Color
- CompilerInvocationInterceptor
- ConfigurationPropertyModel
- DefaultTestService
- GenericTestService
- MapTypeModel
- Model
- Parent
- PrimitiveTypeModel
- SimpleTypeModel
- StringArrayList
- TestAnnotation
- TestService
- TestServiceImpl
jdk-tools
lang-model