]> git.lizzy.rs Git - rust.git/blob - library/std/src/time/tests.rs
Auto merge of #100801 - Kobzol:track-pgo-profile-paths, r=michaelwoerister
[rust.git] / library / std / src / time / tests.rs
1 use super::{Duration, Instant, SystemTime, UNIX_EPOCH};
2 #[cfg(not(target_arch = "wasm32"))]
3 use test::{black_box, Bencher};
4
5 macro_rules! assert_almost_eq {
6     ($a:expr, $b:expr) => {{
7         let (a, b) = ($a, $b);
8         if a != b {
9             let (a, b) = if a > b { (a, b) } else { (b, a) };
10             assert!(a - Duration::from_micros(1) <= b, "{:?} is not almost equal to {:?}", a, b);
11         }
12     }};
13 }
14
15 #[test]
16 fn instant_monotonic() {
17     let a = Instant::now();
18     loop {
19         let b = Instant::now();
20         assert!(b >= a);
21         if b > a {
22             break;
23         }
24     }
25 }
26
27 #[test]
28 #[cfg(not(target_arch = "wasm32"))]
29 fn instant_monotonic_concurrent() -> crate::thread::Result<()> {
30     let threads: Vec<_> = (0..8)
31         .map(|_| {
32             crate::thread::spawn(|| {
33                 let mut old = Instant::now();
34                 let count = if cfg!(miri) { 1_000 } else { 5_000_000 };
35                 for _ in 0..count {
36                     let new = Instant::now();
37                     assert!(new >= old);
38                     old = new;
39                 }
40             })
41         })
42         .collect();
43     for t in threads {
44         t.join()?;
45     }
46     Ok(())
47 }
48
49 #[test]
50 fn instant_elapsed() {
51     let a = Instant::now();
52     let _ = a.elapsed();
53 }
54
55 #[test]
56 fn instant_math() {
57     let a = Instant::now();
58     let b = Instant::now();
59     println!("a: {a:?}");
60     println!("b: {b:?}");
61     let dur = b.duration_since(a);
62     println!("dur: {dur:?}");
63     assert_almost_eq!(b - dur, a);
64     assert_almost_eq!(a + dur, b);
65
66     let second = Duration::SECOND;
67     assert_almost_eq!(a - second + second, a);
68     assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a);
69
70     // checked_add_duration will not panic on overflow
71     let mut maybe_t = Some(Instant::now());
72     let max_duration = Duration::from_secs(u64::MAX);
73     // in case `Instant` can store `>= now + max_duration`.
74     for _ in 0..2 {
75         maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
76     }
77     assert_eq!(maybe_t, None);
78
79     // checked_add_duration calculates the right time and will work for another year
80     let year = Duration::from_secs(60 * 60 * 24 * 365);
81     assert_eq!(a + year, a.checked_add(year).unwrap());
82 }
83
84 #[test]
85 fn instant_math_is_associative() {
86     let now = Instant::now();
87     let offset = Duration::from_millis(5);
88     // Changing the order of instant math shouldn't change the results,
89     // especially when the expression reduces to X + identity.
90     assert_eq!((now + offset) - now, (now - now) + offset);
91 }
92
93 #[test]
94 fn instant_duration_since_saturates() {
95     let a = Instant::now();
96     assert_eq!((a - Duration::SECOND).duration_since(a), Duration::ZERO);
97 }
98
99 #[test]
100 fn instant_checked_duration_since_nopanic() {
101     let now = Instant::now();
102     let earlier = now - Duration::SECOND;
103     let later = now + Duration::SECOND;
104     assert_eq!(earlier.checked_duration_since(now), None);
105     assert_eq!(later.checked_duration_since(now), Some(Duration::SECOND));
106     assert_eq!(now.checked_duration_since(now), Some(Duration::ZERO));
107 }
108
109 #[test]
110 fn instant_saturating_duration_since_nopanic() {
111     let a = Instant::now();
112     #[allow(deprecated, deprecated_in_future)]
113     let ret = (a - Duration::SECOND).saturating_duration_since(a);
114     assert_eq!(ret, Duration::ZERO);
115 }
116
117 #[test]
118 fn system_time_math() {
119     let a = SystemTime::now();
120     let b = SystemTime::now();
121     match b.duration_since(a) {
122         Ok(Duration::ZERO) => {
123             assert_almost_eq!(a, b);
124         }
125         Ok(dur) => {
126             assert!(b > a);
127             assert_almost_eq!(b - dur, a);
128             assert_almost_eq!(a + dur, b);
129         }
130         Err(dur) => {
131             let dur = dur.duration();
132             assert!(a > b);
133             assert_almost_eq!(b + dur, a);
134             assert_almost_eq!(a - dur, b);
135         }
136     }
137
138     let second = Duration::SECOND;
139     assert_almost_eq!(a.duration_since(a - second).unwrap(), second);
140     assert_almost_eq!(a.duration_since(a + second).unwrap_err().duration(), second);
141
142     assert_almost_eq!(a - second + second, a);
143     assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a);
144
145     let one_second_from_epoch = UNIX_EPOCH + Duration::SECOND;
146     let one_second_from_epoch2 =
147         UNIX_EPOCH + Duration::from_millis(500) + Duration::from_millis(500);
148     assert_eq!(one_second_from_epoch, one_second_from_epoch2);
149
150     // checked_add_duration will not panic on overflow
151     let mut maybe_t = Some(SystemTime::UNIX_EPOCH);
152     let max_duration = Duration::from_secs(u64::MAX);
153     // in case `SystemTime` can store `>= UNIX_EPOCH + max_duration`.
154     for _ in 0..2 {
155         maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
156     }
157     assert_eq!(maybe_t, None);
158
159     // checked_add_duration calculates the right time and will work for another year
160     let year = Duration::from_secs(60 * 60 * 24 * 365);
161     assert_eq!(a + year, a.checked_add(year).unwrap());
162 }
163
164 #[test]
165 fn system_time_elapsed() {
166     let a = SystemTime::now();
167     drop(a.elapsed());
168 }
169
170 #[test]
171 fn since_epoch() {
172     let ts = SystemTime::now();
173     let a = ts.duration_since(UNIX_EPOCH + Duration::SECOND).unwrap();
174     let b = ts.duration_since(UNIX_EPOCH).unwrap();
175     assert!(b > a);
176     assert_eq!(b - a, Duration::SECOND);
177
178     let thirty_years = Duration::SECOND * 60 * 60 * 24 * 365 * 30;
179
180     // Right now for CI this test is run in an emulator, and apparently the
181     // aarch64 emulator's sense of time is that we're still living in the
182     // 70s. This is also true for riscv (also qemu)
183     //
184     // Otherwise let's assume that we're all running computers later than
185     // 2000.
186     if !cfg!(target_arch = "aarch64") && !cfg!(target_arch = "riscv64") {
187         assert!(a > thirty_years);
188     }
189
190     // let's assume that we're all running computers earlier than 2090.
191     // Should give us ~70 years to fix this!
192     let hundred_twenty_years = thirty_years * 4;
193     assert!(a < hundred_twenty_years);
194 }
195
196 macro_rules! bench_instant_threaded {
197     ($bench_name:ident, $thread_count:expr) => {
198         #[bench]
199         #[cfg(not(target_arch = "wasm32"))]
200         fn $bench_name(b: &mut Bencher) -> crate::thread::Result<()> {
201             use crate::sync::atomic::{AtomicBool, Ordering};
202             use crate::sync::Arc;
203
204             let running = Arc::new(AtomicBool::new(true));
205
206             let threads: Vec<_> = (0..$thread_count)
207                 .map(|_| {
208                     let flag = Arc::clone(&running);
209                     crate::thread::spawn(move || {
210                         while flag.load(Ordering::Relaxed) {
211                             black_box(Instant::now());
212                         }
213                     })
214                 })
215                 .collect();
216
217             b.iter(|| {
218                 let a = Instant::now();
219                 let b = Instant::now();
220                 assert!(b >= a);
221             });
222
223             running.store(false, Ordering::Relaxed);
224
225             for t in threads {
226                 t.join()?;
227             }
228             Ok(())
229         }
230     };
231 }
232
233 bench_instant_threaded!(instant_contention_01_threads, 0);
234 bench_instant_threaded!(instant_contention_02_threads, 1);
235 bench_instant_threaded!(instant_contention_04_threads, 3);
236 bench_instant_threaded!(instant_contention_08_threads, 7);
237 bench_instant_threaded!(instant_contention_16_threads, 15);