]> git.lizzy.rs Git - rust.git/blob - tests/run-pass/time.rs
ae287234d177465fef09eef4fef7fe389d5451fc
[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 #[cfg(unix)]
12 fn test_sleep() {
13     let before = Instant::now();
14     std::thread::sleep(Duration::from_millis(100));
15     let after = Instant::now();
16     assert!((after - before).as_millis() >= 100);
17 }
18
19 fn main() {
20     // Check `SystemTime`.
21     let now1 = SystemTime::now();
22     let seconds_since_epoch = now1.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs();
23     let years_since_epoch = seconds_since_epoch / 3600 / 24 / 365;
24     let year = 1970 + years_since_epoch;
25     assert!(2020 <= year && year < 2100);
26     // Do some work to make time pass.
27     for _ in 0..10 { drop(vec![42]); }
28     let now2 = SystemTime::now();
29     assert!(now2 > now1);
30     // Sanity-check the difference we got.
31     let diff = now2.duration_since(now1).unwrap();
32     assert_eq!(now1 + diff, now2);
33     assert_eq!(now2 - diff, now1);
34     duration_sanity(diff);
35
36     // Check `Instant`.
37     let now1 = Instant::now();
38     // Do some work to make time pass.
39     for _ in 0..10 { drop(vec![42]); }
40     let now2 = Instant::now();
41     assert!(now2 > now1);
42     // Sanity-check the difference we got.
43     let diff = now2.duration_since(now1);
44     assert_eq!(now1 + diff, now2);
45     assert_eq!(now2 - diff, now1);
46     duration_sanity(diff);
47
48     #[cfg(unix)]
49     test_sleep();
50 }