|
1 | 1 | // compile-flags: -Zmiri-disable-isolation
|
2 | 2 |
|
3 |
| -use std::time::{SystemTime, Instant}; |
| 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 | +} |
4 | 10 |
|
5 | 11 | fn main() {
|
6 | 12 | // Check `SystemTime`.
|
7 | 13 | let now1 = SystemTime::now();
|
| 14 | + let seconds_since_epoch = now1.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs(); |
| 15 | + let years_since_epoch = seconds_since_epoch / 3600 / 24 / 365; |
| 16 | + let year = 1970 + years_since_epoch; |
| 17 | + assert!(2020 <= year && year < 2100); |
8 | 18 | // Do some work to make time pass.
|
9 | 19 | for _ in 0..10 { drop(vec![42]); }
|
10 | 20 | let now2 = SystemTime::now();
|
11 | 21 | assert!(now2 > now1);
|
| 22 | + // Sanity-check the difference we got. |
12 | 23 | let diff = now2.duration_since(now1).unwrap();
|
13 | 24 | assert_eq!(now1 + diff, now2);
|
14 | 25 | assert_eq!(now2 - diff, now1);
|
15 |
| - // Sanity-check the time we got. |
16 |
| - let seconds_since_epoch = now1.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs(); |
17 |
| - let years_since_epoch = seconds_since_epoch / 3600 / 24 / 365; |
18 |
| - let year = 1970 + years_since_epoch; |
19 |
| - assert!(2020 <= year && year < 2100); |
| 26 | + duration_sanity(diff); |
20 | 27 |
|
21 | 28 | // Check `Instant`.
|
22 | 29 | let now1 = Instant::now();
|
23 | 30 | // Do some work to make time pass.
|
24 | 31 | for _ in 0..10 { drop(vec![42]); }
|
25 | 32 | let now2 = Instant::now();
|
26 | 33 | assert!(now2 > now1);
|
| 34 | + // Sanity-check the difference we got. |
27 | 35 | let diff = now2.duration_since(now1);
|
28 | 36 | assert_eq!(now1 + diff, now2);
|
29 | 37 | assert_eq!(now2 - diff, now1);
|
30 |
| - // Sanity-check the difference we got. |
31 |
| - assert!(diff.as_micros() > 1); |
32 |
| - assert!(diff.as_micros() < 1_000_000); |
| 38 | + duration_sanity(diff); |
33 | 39 | }
|
0 commit comments