Stopwatch
Standard library class · Made with Stopwatch.start()
A Stopwatch measures how long something takes. It reads the computer’s steady clock, which only
moves forward, so a change to the computer’s date or time partway through can’t make a measurement
wrong or negative. For the time of day, use Instant.now() instead.
const watch = Stopwatch.start()var total = 0for number in 1..100000 { total += number}print(total)print(watch.elapsed() < Duration(seconds: 5))5000050000trueA Stopwatch is a class rather than a value, since it is a running thing. Stopwatch() isn’t allowed;
Emerald points you to Stopwatch.start(). A stopwatch prints as Stopwatch(1.25s), showing the time
so far.
To pause a program rather than measure it, see Program.sleep.
At a glance
Section titled “At a glance”| Making one | |
|---|---|
Stopwatch.start() |
A stopwatch that starts now |
| Reading | |
|---|---|
elapsed() |
The time since it started |
restart() |
Start measuring again from now |
Making one
Section titled “Making one”A stopwatch that starts at once.
Reading
Section titled “Reading”The time since the stopwatch started, or was last restarted, as a Duration. It is
read afresh at each call, which is why it is a method with parentheses: its answer changes by itself.
const watch = Stopwatch.start()const first = watch.elapsed()const second = watch.elapsed()print(second >= first)trueStarts measuring again from now, as if the stopwatch had just been made.
const watch = Stopwatch.start()watch.restart()print(watch.elapsed() < Duration(seconds: 5))true