]> git.lizzy.rs Git - rust.git/blob - tests/run-pass/time.rs
Review comments
[rust.git] / tests / run-pass / time.rs
1 // compile-flags: -Zmiri-disable-isolation
2
3 use std::time::{SystemTime, Instant, Duration};
4
5 fn duration_sanity(diff: Duration) {
6     // On my laptop, I observed times around 15-40ms. Add 10x lee-way both ways.
7     assert!(diff.as_millis() > 1);
8     assert!(diff.as_millis() < 500);
9 }
10
11 // Thus far, only `libc::nanosleep`, is implemented, not `c::Sleep`.
12 #[cfg(unix)]
13 fn test_sleep() {
14     let before = Instant::now();
15     std::thread::sleep(Duration::from_millis(100));
16     let after = Instant::now();
17     assert!((after - before).as_millis() >= 100);
18 }
19
20 fn main() {
21     // Check `SystemTime`.
22     let now1 = SystemTime::now();
23     let seconds_since_epoch = now1.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
24     let years_since_epoch = seconds_since_epoch / 3600 / 24 / 365;
25     let year = 1970 + years_since_epoch;
26     assert!(2020 <= year && year < 2100);
27     // Do some work to make time pass.
28     for _ in 0..10 { drop(vec![42]); }
29     let now2 = SystemTime::now();
30     assert!(now2 > now1);
31     // Sanity-check the difference we got.
32     let diff = now2.duration_since(now1).unwrap();
33     assert_eq!(now1 + diff, now2);
34     assert_eq!(now2 - diff, now1);
35     duration_sanity(diff);
36
37     // Check `Instant`.
38     let now1 = Instant::now();
39     // Do some work to make time pass.
40     for _ in 0..10 { drop(vec![42]); }
41     let now2 = Instant::now();
42     assert!(now2 > now1);
43     // Sanity-check the difference we got.
44     let diff = now2.duration_since(now1);
45     assert_eq!(now1 + diff, now2);
46     assert_eq!(now2 - diff, now1);
47     duration_sanity(diff);
48
49     #[cfg(unix)]
50     test_sleep();
51 }