Skip to content

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 = 0
for number in 1..100000 {
total += number
}
print(total)
print(watch.elapsed() < Duration(seconds: 5))
Output
5000050000
true

A 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.

Making one
Stopwatch.start() A stopwatch that starts now
Reading
elapsed() The time since it started
restart() Start measuring again from now

Stopwatch.start(): Stopwatch

A stopwatch that starts at once.

elapsed(): Duration

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)
Output
true

restart()

Starts measuring again from now, as if the stopwatch had just been made.

const watch = Stopwatch.start()
watch.restart()
print(watch.elapsed() < Duration(seconds: 5))
Output
true