Stopwatch
A stopwatch, capable of stopping AND watching. This class provides functionality for measuring elapsed time, recording lap times, and managing a sequence of timestamps.
Methods
Stopwatch()
Constructs a new Stopwatch. The timer does not start automatically upon construction.
now()
Static factory method. Creates and starts a new Stopwatch instance at the current time.
start()
Starts or resets the stopwatch. This clears any previously recorded laps and sets the starting timestamp to the current time. The stopwatch is no longer stopped after calling this method.
lap()
Records a lap by adding a new Timestamp at the current time to the list of timestamps, provided the stopwatch is not stopped.
stop()
Adds one final lap to the stopwatch and sets the isStopped flag to true, preventing further laps from being added until start() is called again.
lap(int index)
Returns a String representation of the timestamp at the specified index. Index 0 represents the start time.
elapsedSince(int index)
Calculates the amount of time (in milliseconds) elapsed between the start of the stopwatch (index 0) and the timestamp at the given index. Returns 0 if the index is less than or equal to 1.
laps()
Returns the total number of timestamps (including the start time) recorded by the stopwatch.
elapsed()
Calculates the total amount of time (in milliseconds) elapsed between the first and last recorded timestamps. Throws a RuntimeException if the stopwatch has not been started.
getTimestamps()
Returns the internal List of Timestamp objects recorded by the stopwatch.
getTimes()
Returns a List of Double values, where each value represents the time (in milliseconds) of a recorded timestamp.
toString()
Returns a formatted string representation of the Stopwatch, listing each lap time and the total elapsed time.