stopwatch
The stopwatch package provides Stopwatch, a timer you can start, stop, reset and lap.
watch = stopwatch::start() # create and start in one step
task::sleep(20)first = watch.lap() # milliseconds since the starttask::sleep(10)watch.lap()watch.stop()
println watch.laps().size() # 2println watch.elapsed_ms() >= 30 # trueprintln watch.to_string() # e.g. 30.61ms| Method | Does |
|---|---|
Stopwatch.new() | Creates a stopped stopwatch. stopwatch::start() creates a running one. |
start(), stop() | Starts timing from zero, or freezes the elapsed time. |
reset() | Clears the elapsed time and laps. |
elapsed_ms() | The elapsed time in milliseconds. |
lap() | Records and returns the time of the current lap. |
laps() | The recorded lap times. |
to_string() | The elapsed time formatted for display. |
For timing code over many runs with statistics, use bench. For raw timestamps, see time::ticks.
Functions
Section titled “Functions”stopwatch::new
Section titled “stopwatch::new”stopwatch::new(): StopwatchCreates a new, unstarted Stopwatch.
Returns Stopwatch — A new Stopwatch instance.
stopwatch::start
Section titled “stopwatch::start”stopwatch::start(): StopwatchCreates a new Stopwatch and immediately starts it.
Returns Stopwatch — A running Stopwatch instance.
Stopwatch struct
Section titled “Stopwatch struct”A stopwatch struct for measuring elapsed time.
sw = stopwatch::start()# ... code to time ...println sw.elapsed_ms() # e.g. 42.3
sw.stop()println sw.elapsed_ms() # frozen at stop time
sw.reset()sw.start()lap1 = sw.lap()# ... more code ...lap2 = sw.lap()println sw.laps() # [lap1_ms, lap2_ms].start
Section titled “.start”start()Starts (or restarts) the stopwatch, clearing any previous laps.
stop()Stops the stopwatch, freezing the elapsed time.
.reset
Section titled “.reset”reset()Resets the stopwatch to its initial state.
.elapsed_ms
Section titled “.elapsed_ms”elapsed_ms(): floatReturns elapsed time in milliseconds. If running, returns time since start. If stopped, returns frozen elapsed time.
Returns float — Elapsed milliseconds.
lap(): floatRecords a lap and returns the duration of that lap in milliseconds. Each lap is measured from the previous lap (or from start for the first lap).
Returns float — Lap duration in milliseconds.
laps(): listReturns a list of all recorded lap durations in milliseconds.
Returns list — List of float lap durations.
.to_string
Section titled “.to_string”to_string(): stringReturns a string representation of the current elapsed time.
Returns string — e.g. "42.3ms"