clock
import std::time::clock; · source
Instant
type struct Instant {
secs: i64;
nanos: i64;
static now() -> Instant;
duration_since(&this, earlier: &Instant) -> Duration;
saturating_duration_since(&this, earlier: &Instant) -> Duration;
elapsed(&this) -> Duration;
as_nanos(&this) -> i64;
checked_add(&this, dur: &Duration) -> Option<Instant>;
checked_sub(&this, dur: &Duration) -> Option<Instant>;
}
The monotonic clock. Instant only ever moves forward, which makes it the right tool for measuring elapsed time. It is opaque: a single reading is meaningful only relative to another one.
const start: Instant = Instant::now();
do_work();
println(f"took {start.elapsed()}");
| Method | Returns |
|---|---|
now() | Instant |
elapsed() | Duration from this reading until now. |
duration_since(earlier) | Duration from earlier to this. saturating_duration_since is an alias naming the saturation explicitly. |
as_nanos() | i64 raw monotonic nanoseconds, from an unspecified epoch — for lightweight elapsed math where carrying a Duration is overkill. |
checked_add(dur) / checked_sub(dur) | Option<Instant>, None on overflow or on going below zero. |
Underneath it is CLOCK_MONOTONIC via clock_gettime on POSIX, and QueryPerformanceCounter scaled by QueryPerformanceFrequency on Windows.
Trait implementations
implement trait Eq for struct Instant
implement trait Ord for struct Instant
SystemTime
type struct SystemTime {
secs: i64;
nanos: i64;
static now() -> SystemTime;
static unix_epoch() -> SystemTime;
static from_unix_secs(secs: i64) -> SystemTime;
unix_secs(&this) -> i64;
duration_since_epoch(&this) -> Duration;
duration_since(&this, earlier: &SystemTime) -> Duration;
checked_add(&this, dur: &Duration) -> Option<SystemTime>;
}
The wall clock. SystemTime is subject to NTP steps and manual changes, so it is not for measuring elapsed time. Use it when you need an actual date.
| Method | Returns |
|---|---|
now() / unix_epoch() | SystemTime |
from_unix_secs(secs) | SystemTime |
unix_secs() | i64 — whole seconds since the epoch, negative before 1970. |
duration_since_epoch() | Duration — saturates at zero for a clock set before 1970. |
duration_since(earlier) | Duration — only meaningful if the clock has not been stepped in between. |
checked_add(dur) | Option<SystemTime> |
POSIX reads CLOCK_REALTIME; Windows uses GetSystemTimePreciseAsFileTime and converts from FILETIME ticks since 1601 to the Unix epoch. SystemTime has no Eq or Ord impl — compare through unix_secs or duration_since.
sleep
function sleep(dur: Duration) -> void;
sleep parks the calling thread for at least dur.
The POSIX path uses nanosleep and restarts across EINTR using the kernel's remaining-time readout, so a signal does not cut the sleep short. Windows uses Sleep, which is uninterruptible at the millisecond granularity it accepts; a sub-millisecond request rounds up to 1 ms there, so a non-zero request always blocks.