1 #[cfg(feature = "thread")] 2 use rustix::thread::nanosleep; 3 use rustix::time::{clock_gettime, ClockId, Timespec}; 4 5 /// Attempt to test that the monotonic clock is monotonic. Time may or may not 6 /// advance, but it shouldn't regress. 7 #[test] test_monotonic_clock()8fn test_monotonic_clock() { 9 let a = clock_gettime(ClockId::Monotonic); 10 let b = clock_gettime(ClockId::Monotonic); 11 if b.tv_sec == a.tv_sec { 12 assert!(b.tv_nsec >= a.tv_nsec); 13 } else { 14 assert!(b.tv_sec > a.tv_sec); 15 } 16 } 17 18 /// With the "thread" feature, we can sleep so that we're guaranteed that time 19 /// has advanced. 20 #[cfg(feature = "thread")] 21 #[test] test_monotonic_clock_with_sleep_1s()22fn test_monotonic_clock_with_sleep_1s() { 23 let a = clock_gettime(ClockId::Monotonic); 24 let _rem = nanosleep(&Timespec { 25 tv_sec: 1, 26 tv_nsec: 0, 27 }); 28 let b = clock_gettime(ClockId::Monotonic); 29 assert!(b.tv_sec > a.tv_sec); 30 } 31 32 /// With the "thread" feature, we can sleep so that we're guaranteed that time 33 /// has advanced. 34 #[cfg(feature = "thread")] 35 #[test] test_monotonic_clock_with_sleep_1ms()36fn test_monotonic_clock_with_sleep_1ms() { 37 let a = clock_gettime(ClockId::Monotonic); 38 let _rem = nanosleep(&Timespec { 39 tv_sec: 0, 40 tv_nsec: 1_000_000, 41 }); 42 let b = clock_gettime(ClockId::Monotonic); 43 assert!(b.tv_sec >= a.tv_sec); 44 assert!(b.tv_sec != a.tv_sec || b.tv_nsec > a.tv_nsec); 45 } 46