nylon.time
nylon.time measures time and waits. A Duration is a span of time, now() gives an Instant, a moment, and sleep
waits.
Duration
A Duration is made by a unit member on a whole number. The unit members need no import.
| Member | What it does |
|---|---|
n.nanoseconds(), n.microseconds(), n.milliseconds(), n.seconds(), n.minutes() | n of that unit, as a Duration |
d.nanoseconds | How long d is, in nanoseconds, as an i64 |
a + b, a - b | Two durations added, or one taken from the other |
==, !=, <, <=, >, >= | Compare two durations |
let short = 200.milliseconds()
let long = 2.seconds()
let both = short + long
println(both.nanoseconds)
println(short < long)
2200000000
true
A unit member takes a whole number, so a second and a half is 1500 milliseconds. A duration is added to and taken from another duration, not multiplied.
A duration doesn't multiply by a number:
let twice = 2.seconds() * 2
now() and Instant
now() gives an Instant: the moment it's called, counted from when the board started, never going back. Subtracting
one instant from a later one gives the Duration between them.
| Form | What it does |
|---|---|
now() | This moment, as an Instant |
later - start | The time between two instants, as a Duration |
start + d, later - d | The instant a duration after, or before |
==, !=, <, <=, >, >= | Compare two instants |
now() and sleep come from nylon.time, so a program imports it:
import namespace nylon.time
let start = now()
sleep(10.milliseconds())
let took = now() - start
println("that took ${took.nanoseconds} ns")
An instant has no number of its own to read: measure a duration from another instant, as now() - start does.
import namespace nylon.time
let deadline = now() + 1.seconds()
while (now() < deadline) {
sleep(100.milliseconds())
}
sleep
sleep(duration: Duration) waits for the duration, and then the program carries on. A duration of zero or less
returns at once.
import namespace nylon.time
sleep(500.milliseconds())
sleep takes a Duration, not a number. The build says to write 500.milliseconds():
import namespace nylon.time
sleep(500)