Time
Duration values for async timers and deadlines.
std.time contains Duration, the opaque value used by async timers and
deadlines. Build durations with unit constructors and pass them to
future.sleep or future.timeout.
import std.future;
import std.time;
async fn main() {
await future.sleep(time.ns(0));
let value = (await future.timeout(future.ready(7), try time.sec(1))) catch {
_ => 0
};
assert value == 7;
}
time.ns cannot overflow because it stores the input directly as nanoseconds.
time.us, time.ms, and time.sec return
Duration throws(TimeError) because converting to nanoseconds can overflow.
import std.time;
fn main() {
let short = time.ns(3 as u64);
let medium = try time.ms(5 as u64);
assert time.to_nanoseconds(short) == 3 as u64;
assert time.to_nanoseconds(medium) == 5000000 as u64;
}
Use catch when an overflow should become a fallback duration.
import std.time;
fn main() {
let overflowed = false;
let fallback = time.sec(@max(u64)) catch {
.Overflow => {
overflowed = true;
return time.ns(0);
}
};
assert overflowed;
assert time.to_nanoseconds(fallback) == 0 as u64;
}
| Function | Purpose |
|---|---|
time.ns(amount) | Build a nanosecond duration. |
time.us(amount) | Build a microsecond duration or throw TimeError.Overflow. |
time.ms(amount) | Build a millisecond duration or throw TimeError.Overflow. |
time.sec(amount) | Build a second duration or throw TimeError.Overflow. |
time.to_nanoseconds(duration) | Return the raw nanosecond count. |
TimeError currently has one case: Overflow.