system.time
system.time splits time into three types so that a duration can never be confused with a point in time, and neither can be confused with a bare number. A Clock is the capability for reading the wall clock and for sleeping.
use system.io
use system.time
fn main()
// Clock is the capability for reading the wall clock and sleeping.
let clock = Clock()
// Duration is built through static constructors, never a bare number,
// so the unit is always visible at the call site.
let pause = Duration.from_millis(50)
println(f"pausing for {pause.as_millis()} ms")
let started = clock.now()
clock.sleep(pause)
// An Instant measures against the clock it was taken from.
let taken = started.elapsed(clock)
println(f"slept at least 50 ms: {taken.as_millis() >= 50}")
println(f"{Duration.from_seconds(2).as_millis()} ms in two seconds")
| Member | Returns | Behaviour |
|---|---|---|
Duration.from_nanos / from_micros / from_millis / from_seconds | Duration | Static constructors — the unit is named at the call site, never implied. |
as_nanos() / as_micros() / as_millis() / as_seconds() | int | Reads a Duration back in a chosen unit. |
Clock().now() | Instant | A point in time. |
Clock().sleep(d Duration) | — | Blocks for at least d. |
Instant.elapsed(clock Clock) | Duration | Time since the instant was taken. |
Those static constructors are what made Duration.from_millis(500) possible: static class members shipped as the language feature this module needed.