sched_clock/clocks/
std.rs

1//! Clock implementation based on the Rust standard library
2
3use crate::{Clock, Instant};
4use std::convert::TryInto;
5
6/// Clock implementation based on the Rust standard library
7///
8/// Guaranteed to be there on any system supported by the Rust standard library
9/// and to be monotonic (never jump back in time), but durations may inflate or
10/// shrink during clock calibration events (e.g. NTP synchronization), and there
11/// are no guarantee about precision or correct suspend handling.
12///
13pub struct StdClock(std::time::Instant);
14
15impl Default for StdClock {
16    fn default() -> Self {
17        Self(std::time::Instant::now())
18    }
19}
20
21impl Clock for StdClock {
22    fn now(&self) -> Instant {
23        let elapsed_nanos = self.0.elapsed().as_nanos();
24        let elapsed_nanos: i64 = elapsed_nanos
25            .try_into()
26            .expect("Either ~300 years have elapsed or std::time has a bug!");
27        Instant(elapsed_nanos)
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    #[test]
34    fn std_clock() {
35        crate::clocks::tests::generic_clock_test::<super::StdClock>();
36    }
37}