sched_clock/clocks/mod.rs
1//! Clocks providing Instants to this library
2//!
3//! Instants (i.e. time points) can come from various sources. The Rust stdlib
4//! is one of them, but we expect to add more in the future, which provide
5//! additional performance and/or correctness on specific systems.
6
7#[cfg(target_os = "linux")]
8pub mod linux;
9mod std;
10
11use crate::Instant;
12
13// Reexport the StdClock, there is no point exporting the whole std module as
14// it's the only thing inside of it.
15pub use self::std::StdClock;
16
17/// Common interface shared by all Clocks provided by this library
18pub trait Clock: Default {
19 /// Get an Instant representing the current time
20 ///
21 /// Instants should be above `Instant::EPOCH` and monotonically increasing,
22 /// but low-quality clocks may slow down and speed up slightly as they try
23 /// to synchronize themselves with other clocks. Good timestamp clocks will
24 /// prevent this and always deliver 100% steady time.
25 ///
26 fn now(&self) -> Instant;
27}
28
29/// Recommended choice of Clock for your system
30#[cfg(not(target_os = "linux"))]
31pub type DefaultClock = StdClock;
32
33/// Recommended choice of Clock for Linux systems
34#[cfg(target_os = "linux")]
35pub type DefaultClock = linux::BootTimeClock;
36
37#[cfg(test)]
38pub(crate) mod tests {
39 use super::*;
40 use crate::{Clock, Duration, Instant};
41
42 /// Generic test for a Clock
43 pub(crate) fn generic_clock_test<C: Clock>() {
44 // Default-construct a clock
45 let clock = C::default();
46
47 // First time point
48 let t1 = clock.now();
49 assert!(t1 >= Instant::EPOCH);
50 assert!(t1 < Instant::SOMEDAY);
51
52 // Second time point
53 let t2 = clock.now();
54 assert!(t2 >= t1);
55 assert!(t2 < Instant::SOMEDAY);
56
57 // Any self-respecting clock should have at least millisecond resolution
58 ::std::thread::sleep(::std::time::Duration::from_millis(2));
59 let t3 = clock.now();
60 assert!(t3 > t2 + Duration::MILLISECOND);
61 assert!(t3 < Instant::SOMEDAY);
62 }
63
64 /// Test the default clock in this way
65 #[test]
66 fn default_clock() {
67 generic_clock_test::<DefaultClock>();
68 }
69}