1 | //! Temporal quantification. |
2 | //! |
3 | //! # Examples |
4 | //! |
5 | //! There are multiple ways to create a new [`Duration`]: |
6 | //! |
7 | //! ``` |
8 | //! # use std::time::Duration; |
9 | //! let five_seconds = Duration::from_secs(5); |
10 | //! assert_eq!(five_seconds, Duration::from_millis(5_000)); |
11 | //! assert_eq!(five_seconds, Duration::from_micros(5_000_000)); |
12 | //! assert_eq!(five_seconds, Duration::from_nanos(5_000_000_000)); |
13 | //! |
14 | //! let ten_seconds = Duration::from_secs(10); |
15 | //! let seven_nanos = Duration::from_nanos(7); |
16 | //! let total = ten_seconds + seven_nanos; |
17 | //! assert_eq!(total, Duration::new(10, 7)); |
18 | //! ``` |
19 | //! |
20 | //! Using [`Instant`] to calculate how long a function took to run: |
21 | //! |
22 | //! ```ignore (incomplete) |
23 | //! let now = Instant::now(); |
24 | //! |
25 | //! // Calling a slow function, it may take a while |
26 | //! slow_function(); |
27 | //! |
28 | //! let elapsed_time = now.elapsed(); |
29 | //! println!("Running slow_function() took {} seconds." , elapsed_time.as_secs()); |
30 | //! ``` |
31 | |
32 | #![stable (feature = "time" , since = "1.3.0" )] |
33 | |
34 | #[cfg (test)] |
35 | mod tests; |
36 | |
37 | use crate::error::Error; |
38 | use crate::fmt; |
39 | use crate::ops::{Add, AddAssign, Sub, SubAssign}; |
40 | use crate::sys::time; |
41 | use crate::sys_common::{FromInner, IntoInner}; |
42 | |
43 | #[stable (feature = "time" , since = "1.3.0" )] |
44 | pub use core::time::Duration; |
45 | |
46 | #[stable (feature = "duration_checked_float" , since = "1.66.0" )] |
47 | pub use core::time::TryFromFloatSecsError; |
48 | |
49 | /// A measurement of a monotonically nondecreasing clock. |
50 | /// Opaque and useful only with [`Duration`]. |
51 | /// |
52 | /// Instants are always guaranteed, barring [platform bugs], to be no less than any previously |
53 | /// measured instant when created, and are often useful for tasks such as measuring |
54 | /// benchmarks or timing how long an operation takes. |
55 | /// |
56 | /// Note, however, that instants are **not** guaranteed to be **steady**. In other |
57 | /// words, each tick of the underlying clock might not be the same length (e.g. |
58 | /// some seconds may be longer than others). An instant may jump forwards or |
59 | /// experience time dilation (slow down or speed up), but it will never go |
60 | /// backwards. |
61 | /// As part of this non-guarantee it is also not specified whether system suspends count as |
62 | /// elapsed time or not. The behavior varies across platforms and Rust versions. |
63 | /// |
64 | /// Instants are opaque types that can only be compared to one another. There is |
65 | /// no method to get "the number of seconds" from an instant. Instead, it only |
66 | /// allows measuring the duration between two instants (or comparing two |
67 | /// instants). |
68 | /// |
69 | /// The size of an `Instant` struct may vary depending on the target operating |
70 | /// system. |
71 | /// |
72 | /// Example: |
73 | /// |
74 | /// ```no_run |
75 | /// use std::time::{Duration, Instant}; |
76 | /// use std::thread::sleep; |
77 | /// |
78 | /// fn main() { |
79 | /// let now = Instant::now(); |
80 | /// |
81 | /// // we sleep for 2 seconds |
82 | /// sleep(Duration::new(2, 0)); |
83 | /// // it prints '2' |
84 | /// println!("{}" , now.elapsed().as_secs()); |
85 | /// } |
86 | /// ``` |
87 | /// |
88 | /// [platform bugs]: Instant#monotonicity |
89 | /// |
90 | /// # OS-specific behaviors |
91 | /// |
92 | /// An `Instant` is a wrapper around system-specific types and it may behave |
93 | /// differently depending on the underlying operating system. For example, |
94 | /// the following snippet is fine on Linux but panics on macOS: |
95 | /// |
96 | /// ```no_run |
97 | /// use std::time::{Instant, Duration}; |
98 | /// |
99 | /// let now = Instant::now(); |
100 | /// let max_seconds = u64::MAX / 1_000_000_000; |
101 | /// let duration = Duration::new(max_seconds, 0); |
102 | /// println!("{:?}" , now + duration); |
103 | /// ``` |
104 | /// |
105 | /// # Underlying System calls |
106 | /// |
107 | /// The following system calls are [currently] being used by `now()` to find out |
108 | /// the current time: |
109 | /// |
110 | /// | Platform | System call | |
111 | /// |-----------|----------------------------------------------------------------------| |
112 | /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] | |
113 | /// | UNIX | [clock_gettime (Monotonic Clock)] | |
114 | /// | Darwin | [clock_gettime (Monotonic Clock)] | |
115 | /// | VXWorks | [clock_gettime (Monotonic Clock)] | |
116 | /// | SOLID | `get_tim` | |
117 | /// | WASI | [__wasi_clock_time_get (Monotonic Clock)] | |
118 | /// | Windows | [QueryPerformanceCounter] | |
119 | /// |
120 | /// [currently]: crate::io#platform-specific-behavior |
121 | /// [QueryPerformanceCounter]: https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter |
122 | /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time |
123 | /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode |
124 | /// [__wasi_clock_time_get (Monotonic Clock)]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#clock_time_get |
125 | /// [clock_gettime (Monotonic Clock)]: https://linux.die.net/man/3/clock_gettime |
126 | /// |
127 | /// **Disclaimer:** These system calls might change over time. |
128 | /// |
129 | /// > Note: mathematical operations like [`add`] may panic if the underlying |
130 | /// > structure cannot represent the new point in time. |
131 | /// |
132 | /// [`add`]: Instant::add |
133 | /// |
134 | /// ## Monotonicity |
135 | /// |
136 | /// On all platforms `Instant` will try to use an OS API that guarantees monotonic behavior |
137 | /// if available, which is the case for all [tier 1] platforms. |
138 | /// In practice such guarantees are – under rare circumstances – broken by hardware, virtualization |
139 | /// or operating system bugs. To work around these bugs and platforms not offering monotonic clocks |
140 | /// [`duration_since`], [`elapsed`] and [`sub`] saturate to zero. In older Rust versions this |
141 | /// lead to a panic instead. [`checked_duration_since`] can be used to detect and handle situations |
142 | /// where monotonicity is violated, or `Instant`s are subtracted in the wrong order. |
143 | /// |
144 | /// This workaround obscures programming errors where earlier and later instants are accidentally |
145 | /// swapped. For this reason future Rust versions may reintroduce panics. |
146 | /// |
147 | /// [tier 1]: https://doc.rust-lang.org/rustc/platform-support.html |
148 | /// [`duration_since`]: Instant::duration_since |
149 | /// [`elapsed`]: Instant::elapsed |
150 | /// [`sub`]: Instant::sub |
151 | /// [`checked_duration_since`]: Instant::checked_duration_since |
152 | /// |
153 | #[derive (Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] |
154 | #[stable (feature = "time2" , since = "1.8.0" )] |
155 | #[cfg_attr (not(test), rustc_diagnostic_item = "Instant" )] |
156 | pub struct Instant(time::Instant); |
157 | |
158 | /// A measurement of the system clock, useful for talking to |
159 | /// external entities like the file system or other processes. |
160 | /// |
161 | /// Distinct from the [`Instant`] type, this time measurement **is not |
162 | /// monotonic**. This means that you can save a file to the file system, then |
163 | /// save another file to the file system, **and the second file has a |
164 | /// `SystemTime` measurement earlier than the first**. In other words, an |
165 | /// operation that happens after another operation in real time may have an |
166 | /// earlier `SystemTime`! |
167 | /// |
168 | /// Consequently, comparing two `SystemTime` instances to learn about the |
169 | /// duration between them returns a [`Result`] instead of an infallible [`Duration`] |
170 | /// to indicate that this sort of time drift may happen and needs to be handled. |
171 | /// |
172 | /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`] |
173 | /// constant is provided in this module as an anchor in time to learn |
174 | /// information about a `SystemTime`. By calculating the duration from this |
175 | /// fixed point in time, a `SystemTime` can be converted to a human-readable time, |
176 | /// or perhaps some other string representation. |
177 | /// |
178 | /// The size of a `SystemTime` struct may vary depending on the target operating |
179 | /// system. |
180 | /// |
181 | /// A `SystemTime` does not count leap seconds. |
182 | /// `SystemTime::now()`'s behaviour around a leap second |
183 | /// is the same as the operating system's wall clock. |
184 | /// The precise behaviour near a leap second |
185 | /// (e.g. whether the clock appears to run slow or fast, or stop, or jump) |
186 | /// depends on platform and configuration, |
187 | /// so should not be relied on. |
188 | /// |
189 | /// Example: |
190 | /// |
191 | /// ```no_run |
192 | /// use std::time::{Duration, SystemTime}; |
193 | /// use std::thread::sleep; |
194 | /// |
195 | /// fn main() { |
196 | /// let now = SystemTime::now(); |
197 | /// |
198 | /// // we sleep for 2 seconds |
199 | /// sleep(Duration::new(2, 0)); |
200 | /// match now.elapsed() { |
201 | /// Ok(elapsed) => { |
202 | /// // it prints '2' |
203 | /// println!("{}" , elapsed.as_secs()); |
204 | /// } |
205 | /// Err(e) => { |
206 | /// // an error occurred! |
207 | /// println!("Error: {e:?}" ); |
208 | /// } |
209 | /// } |
210 | /// } |
211 | /// ``` |
212 | /// |
213 | /// # Platform-specific behavior |
214 | /// |
215 | /// The precision of `SystemTime` can depend on the underlying OS-specific time format. |
216 | /// For example, on Windows the time is represented in 100 nanosecond intervals whereas Linux |
217 | /// can represent nanosecond intervals. |
218 | /// |
219 | /// The following system calls are [currently] being used by `now()` to find out |
220 | /// the current time: |
221 | /// |
222 | /// | Platform | System call | |
223 | /// |-----------|----------------------------------------------------------------------| |
224 | /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] | |
225 | /// | UNIX | [clock_gettime (Realtime Clock)] | |
226 | /// | Darwin | [clock_gettime (Realtime Clock)] | |
227 | /// | VXWorks | [clock_gettime (Realtime Clock)] | |
228 | /// | SOLID | `SOLID_RTC_ReadTime` | |
229 | /// | WASI | [__wasi_clock_time_get (Realtime Clock)] | |
230 | /// | Windows | [GetSystemTimePreciseAsFileTime] / [GetSystemTimeAsFileTime] | |
231 | /// |
232 | /// [currently]: crate::io#platform-specific-behavior |
233 | /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time |
234 | /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode |
235 | /// [clock_gettime (Realtime Clock)]: https://linux.die.net/man/3/clock_gettime |
236 | /// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#clock_time_get |
237 | /// [GetSystemTimePreciseAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime |
238 | /// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime |
239 | /// |
240 | /// **Disclaimer:** These system calls might change over time. |
241 | /// |
242 | /// > Note: mathematical operations like [`add`] may panic if the underlying |
243 | /// > structure cannot represent the new point in time. |
244 | /// |
245 | /// [`add`]: SystemTime::add |
246 | #[derive (Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] |
247 | #[stable (feature = "time2" , since = "1.8.0" )] |
248 | pub struct SystemTime(time::SystemTime); |
249 | |
250 | /// An error returned from the `duration_since` and `elapsed` methods on |
251 | /// `SystemTime`, used to learn how far in the opposite direction a system time |
252 | /// lies. |
253 | /// |
254 | /// # Examples |
255 | /// |
256 | /// ```no_run |
257 | /// use std::thread::sleep; |
258 | /// use std::time::{Duration, SystemTime}; |
259 | /// |
260 | /// let sys_time = SystemTime::now(); |
261 | /// sleep(Duration::from_secs(1)); |
262 | /// let new_sys_time = SystemTime::now(); |
263 | /// match sys_time.duration_since(new_sys_time) { |
264 | /// Ok(_) => {} |
265 | /// Err(e) => println!("SystemTimeError difference: {:?}" , e.duration()), |
266 | /// } |
267 | /// ``` |
268 | #[derive (Clone, Debug)] |
269 | #[stable (feature = "time2" , since = "1.8.0" )] |
270 | pub struct SystemTimeError(Duration); |
271 | |
272 | impl Instant { |
273 | /// Returns an instant corresponding to "now". |
274 | /// |
275 | /// # Examples |
276 | /// |
277 | /// ``` |
278 | /// use std::time::Instant; |
279 | /// |
280 | /// let now = Instant::now(); |
281 | /// ``` |
282 | #[must_use ] |
283 | #[stable (feature = "time2" , since = "1.8.0" )] |
284 | pub fn now() -> Instant { |
285 | Instant(time::Instant::now()) |
286 | } |
287 | |
288 | /// Returns the amount of time elapsed from another instant to this one, |
289 | /// or zero duration if that instant is later than this one. |
290 | /// |
291 | /// # Panics |
292 | /// |
293 | /// Previous Rust versions panicked when `earlier` was later than `self`. Currently this |
294 | /// method saturates. Future versions may reintroduce the panic in some circumstances. |
295 | /// See [Monotonicity]. |
296 | /// |
297 | /// [Monotonicity]: Instant#monotonicity |
298 | /// |
299 | /// # Examples |
300 | /// |
301 | /// ```no_run |
302 | /// use std::time::{Duration, Instant}; |
303 | /// use std::thread::sleep; |
304 | /// |
305 | /// let now = Instant::now(); |
306 | /// sleep(Duration::new(1, 0)); |
307 | /// let new_now = Instant::now(); |
308 | /// println!("{:?}" , new_now.duration_since(now)); |
309 | /// println!("{:?}" , now.duration_since(new_now)); // 0ns |
310 | /// ``` |
311 | #[must_use ] |
312 | #[stable (feature = "time2" , since = "1.8.0" )] |
313 | pub fn duration_since(&self, earlier: Instant) -> Duration { |
314 | self.checked_duration_since(earlier).unwrap_or_default() |
315 | } |
316 | |
317 | /// Returns the amount of time elapsed from another instant to this one, |
318 | /// or None if that instant is later than this one. |
319 | /// |
320 | /// Due to [monotonicity bugs], even under correct logical ordering of the passed `Instant`s, |
321 | /// this method can return `None`. |
322 | /// |
323 | /// [monotonicity bugs]: Instant#monotonicity |
324 | /// |
325 | /// # Examples |
326 | /// |
327 | /// ```no_run |
328 | /// use std::time::{Duration, Instant}; |
329 | /// use std::thread::sleep; |
330 | /// |
331 | /// let now = Instant::now(); |
332 | /// sleep(Duration::new(1, 0)); |
333 | /// let new_now = Instant::now(); |
334 | /// println!("{:?}" , new_now.checked_duration_since(now)); |
335 | /// println!("{:?}" , now.checked_duration_since(new_now)); // None |
336 | /// ``` |
337 | #[must_use ] |
338 | #[stable (feature = "checked_duration_since" , since = "1.39.0" )] |
339 | pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> { |
340 | self.0.checked_sub_instant(&earlier.0) |
341 | } |
342 | |
343 | /// Returns the amount of time elapsed from another instant to this one, |
344 | /// or zero duration if that instant is later than this one. |
345 | /// |
346 | /// # Examples |
347 | /// |
348 | /// ```no_run |
349 | /// use std::time::{Duration, Instant}; |
350 | /// use std::thread::sleep; |
351 | /// |
352 | /// let now = Instant::now(); |
353 | /// sleep(Duration::new(1, 0)); |
354 | /// let new_now = Instant::now(); |
355 | /// println!("{:?}" , new_now.saturating_duration_since(now)); |
356 | /// println!("{:?}" , now.saturating_duration_since(new_now)); // 0ns |
357 | /// ``` |
358 | #[must_use ] |
359 | #[stable (feature = "checked_duration_since" , since = "1.39.0" )] |
360 | pub fn saturating_duration_since(&self, earlier: Instant) -> Duration { |
361 | self.checked_duration_since(earlier).unwrap_or_default() |
362 | } |
363 | |
364 | /// Returns the amount of time elapsed since this instant. |
365 | /// |
366 | /// # Panics |
367 | /// |
368 | /// Previous Rust versions panicked when the current time was earlier than self. Currently this |
369 | /// method returns a Duration of zero in that case. Future versions may reintroduce the panic. |
370 | /// See [Monotonicity]. |
371 | /// |
372 | /// [Monotonicity]: Instant#monotonicity |
373 | /// |
374 | /// # Examples |
375 | /// |
376 | /// ```no_run |
377 | /// use std::thread::sleep; |
378 | /// use std::time::{Duration, Instant}; |
379 | /// |
380 | /// let instant = Instant::now(); |
381 | /// let three_secs = Duration::from_secs(3); |
382 | /// sleep(three_secs); |
383 | /// assert!(instant.elapsed() >= three_secs); |
384 | /// ``` |
385 | #[must_use ] |
386 | #[stable (feature = "time2" , since = "1.8.0" )] |
387 | pub fn elapsed(&self) -> Duration { |
388 | Instant::now() - *self |
389 | } |
390 | |
391 | /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as |
392 | /// `Instant` (which means it's inside the bounds of the underlying data structure), `None` |
393 | /// otherwise. |
394 | #[stable (feature = "time_checked_add" , since = "1.34.0" )] |
395 | pub fn checked_add(&self, duration: Duration) -> Option<Instant> { |
396 | self.0.checked_add_duration(&duration).map(Instant) |
397 | } |
398 | |
399 | /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as |
400 | /// `Instant` (which means it's inside the bounds of the underlying data structure), `None` |
401 | /// otherwise. |
402 | #[stable (feature = "time_checked_add" , since = "1.34.0" )] |
403 | pub fn checked_sub(&self, duration: Duration) -> Option<Instant> { |
404 | self.0.checked_sub_duration(&duration).map(Instant) |
405 | } |
406 | } |
407 | |
408 | #[stable (feature = "time2" , since = "1.8.0" )] |
409 | impl Add<Duration> for Instant { |
410 | type Output = Instant; |
411 | |
412 | /// # Panics |
413 | /// |
414 | /// This function may panic if the resulting point in time cannot be represented by the |
415 | /// underlying data structure. See [`Instant::checked_add`] for a version without panic. |
416 | fn add(self, other: Duration) -> Instant { |
417 | self.checked_add(other).expect(msg:"overflow when adding duration to instant" ) |
418 | } |
419 | } |
420 | |
421 | #[stable (feature = "time_augmented_assignment" , since = "1.9.0" )] |
422 | impl AddAssign<Duration> for Instant { |
423 | fn add_assign(&mut self, other: Duration) { |
424 | *self = *self + other; |
425 | } |
426 | } |
427 | |
428 | #[stable (feature = "time2" , since = "1.8.0" )] |
429 | impl Sub<Duration> for Instant { |
430 | type Output = Instant; |
431 | |
432 | fn sub(self, other: Duration) -> Instant { |
433 | self.checked_sub(other).expect(msg:"overflow when subtracting duration from instant" ) |
434 | } |
435 | } |
436 | |
437 | #[stable (feature = "time_augmented_assignment" , since = "1.9.0" )] |
438 | impl SubAssign<Duration> for Instant { |
439 | fn sub_assign(&mut self, other: Duration) { |
440 | *self = *self - other; |
441 | } |
442 | } |
443 | |
444 | #[stable (feature = "time2" , since = "1.8.0" )] |
445 | impl Sub<Instant> for Instant { |
446 | type Output = Duration; |
447 | |
448 | /// Returns the amount of time elapsed from another instant to this one, |
449 | /// or zero duration if that instant is later than this one. |
450 | /// |
451 | /// # Panics |
452 | /// |
453 | /// Previous Rust versions panicked when `other` was later than `self`. Currently this |
454 | /// method saturates. Future versions may reintroduce the panic in some circumstances. |
455 | /// See [Monotonicity]. |
456 | /// |
457 | /// [Monotonicity]: Instant#monotonicity |
458 | fn sub(self, other: Instant) -> Duration { |
459 | self.duration_since(earlier:other) |
460 | } |
461 | } |
462 | |
463 | #[stable (feature = "time2" , since = "1.8.0" )] |
464 | impl fmt::Debug for Instant { |
465 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
466 | self.0.fmt(f) |
467 | } |
468 | } |
469 | |
470 | impl SystemTime { |
471 | /// An anchor in time which can be used to create new `SystemTime` instances or |
472 | /// learn about where in time a `SystemTime` lies. |
473 | // |
474 | // NOTE! this documentation is duplicated, here and in std::time::UNIX_EPOCH. |
475 | // The two copies are not quite identical, because of the difference in naming. |
476 | /// |
477 | /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with |
478 | /// respect to the system clock. Using `duration_since` on an existing |
479 | /// `SystemTime` instance can tell how far away from this point in time a |
480 | /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a |
481 | /// `SystemTime` instance to represent another fixed point in time. |
482 | /// |
483 | /// `duration_since(UNIX_EPOCH).unwrap().as_secs()` returns |
484 | /// the number of non-leap seconds since the start of 1970 UTC. |
485 | /// This is a POSIX `time_t` (as a `u64`), |
486 | /// and is the same time representation as used in many Internet protocols. |
487 | /// |
488 | /// # Examples |
489 | /// |
490 | /// ```no_run |
491 | /// use std::time::SystemTime; |
492 | /// |
493 | /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) { |
494 | /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!" , n.as_secs()), |
495 | /// Err(_) => panic!("SystemTime before UNIX EPOCH!" ), |
496 | /// } |
497 | /// ``` |
498 | #[stable (feature = "assoc_unix_epoch" , since = "1.28.0" )] |
499 | pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH; |
500 | |
501 | /// Returns the system time corresponding to "now". |
502 | /// |
503 | /// # Examples |
504 | /// |
505 | /// ``` |
506 | /// use std::time::SystemTime; |
507 | /// |
508 | /// let sys_time = SystemTime::now(); |
509 | /// ``` |
510 | #[must_use ] |
511 | #[stable (feature = "time2" , since = "1.8.0" )] |
512 | pub fn now() -> SystemTime { |
513 | SystemTime(time::SystemTime::now()) |
514 | } |
515 | |
516 | /// Returns the amount of time elapsed from an earlier point in time. |
517 | /// |
518 | /// This function may fail because measurements taken earlier are not |
519 | /// guaranteed to always be before later measurements (due to anomalies such |
520 | /// as the system clock being adjusted either forwards or backwards). |
521 | /// [`Instant`] can be used to measure elapsed time without this risk of failure. |
522 | /// |
523 | /// If successful, <code>[Ok]\([Duration])</code> is returned where the duration represents |
524 | /// the amount of time elapsed from the specified measurement to this one. |
525 | /// |
526 | /// Returns an [`Err`] if `earlier` is later than `self`, and the error |
527 | /// contains how far from `self` the time is. |
528 | /// |
529 | /// # Examples |
530 | /// |
531 | /// ```no_run |
532 | /// use std::time::SystemTime; |
533 | /// |
534 | /// let sys_time = SystemTime::now(); |
535 | /// let new_sys_time = SystemTime::now(); |
536 | /// let difference = new_sys_time.duration_since(sys_time) |
537 | /// .expect("Clock may have gone backwards" ); |
538 | /// println!("{difference:?}" ); |
539 | /// ``` |
540 | #[stable (feature = "time2" , since = "1.8.0" )] |
541 | pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> { |
542 | self.0.sub_time(&earlier.0).map_err(SystemTimeError) |
543 | } |
544 | |
545 | /// Returns the difference from this system time to the |
546 | /// current clock time. |
547 | /// |
548 | /// This function may fail as the underlying system clock is susceptible to |
549 | /// drift and updates (e.g., the system clock could go backwards), so this |
550 | /// function might not always succeed. If successful, <code>[Ok]\([Duration])</code> is |
551 | /// returned where the duration represents the amount of time elapsed from |
552 | /// this time measurement to the current time. |
553 | /// |
554 | /// To measure elapsed time reliably, use [`Instant`] instead. |
555 | /// |
556 | /// Returns an [`Err`] if `self` is later than the current system time, and |
557 | /// the error contains how far from the current system time `self` is. |
558 | /// |
559 | /// # Examples |
560 | /// |
561 | /// ```no_run |
562 | /// use std::thread::sleep; |
563 | /// use std::time::{Duration, SystemTime}; |
564 | /// |
565 | /// let sys_time = SystemTime::now(); |
566 | /// let one_sec = Duration::from_secs(1); |
567 | /// sleep(one_sec); |
568 | /// assert!(sys_time.elapsed().unwrap() >= one_sec); |
569 | /// ``` |
570 | #[stable (feature = "time2" , since = "1.8.0" )] |
571 | pub fn elapsed(&self) -> Result<Duration, SystemTimeError> { |
572 | SystemTime::now().duration_since(*self) |
573 | } |
574 | |
575 | /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as |
576 | /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None` |
577 | /// otherwise. |
578 | #[stable (feature = "time_checked_add" , since = "1.34.0" )] |
579 | pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> { |
580 | self.0.checked_add_duration(&duration).map(SystemTime) |
581 | } |
582 | |
583 | /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as |
584 | /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None` |
585 | /// otherwise. |
586 | #[stable (feature = "time_checked_add" , since = "1.34.0" )] |
587 | pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> { |
588 | self.0.checked_sub_duration(&duration).map(SystemTime) |
589 | } |
590 | } |
591 | |
592 | #[stable (feature = "time2" , since = "1.8.0" )] |
593 | impl Add<Duration> for SystemTime { |
594 | type Output = SystemTime; |
595 | |
596 | /// # Panics |
597 | /// |
598 | /// This function may panic if the resulting point in time cannot be represented by the |
599 | /// underlying data structure. See [`SystemTime::checked_add`] for a version without panic. |
600 | fn add(self, dur: Duration) -> SystemTime { |
601 | self.checked_add(dur).expect(msg:"overflow when adding duration to instant" ) |
602 | } |
603 | } |
604 | |
605 | #[stable (feature = "time_augmented_assignment" , since = "1.9.0" )] |
606 | impl AddAssign<Duration> for SystemTime { |
607 | fn add_assign(&mut self, other: Duration) { |
608 | *self = *self + other; |
609 | } |
610 | } |
611 | |
612 | #[stable (feature = "time2" , since = "1.8.0" )] |
613 | impl Sub<Duration> for SystemTime { |
614 | type Output = SystemTime; |
615 | |
616 | fn sub(self, dur: Duration) -> SystemTime { |
617 | self.checked_sub(dur).expect(msg:"overflow when subtracting duration from instant" ) |
618 | } |
619 | } |
620 | |
621 | #[stable (feature = "time_augmented_assignment" , since = "1.9.0" )] |
622 | impl SubAssign<Duration> for SystemTime { |
623 | fn sub_assign(&mut self, other: Duration) { |
624 | *self = *self - other; |
625 | } |
626 | } |
627 | |
628 | #[stable (feature = "time2" , since = "1.8.0" )] |
629 | impl fmt::Debug for SystemTime { |
630 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
631 | self.0.fmt(f) |
632 | } |
633 | } |
634 | |
635 | /// An anchor in time which can be used to create new `SystemTime` instances or |
636 | /// learn about where in time a `SystemTime` lies. |
637 | // |
638 | // NOTE! this documentation is duplicated, here and in SystemTime::UNIX_EPOCH. |
639 | // The two copies are not quite identical, because of the difference in naming. |
640 | /// |
641 | /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with |
642 | /// respect to the system clock. Using `duration_since` on an existing |
643 | /// [`SystemTime`] instance can tell how far away from this point in time a |
644 | /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a |
645 | /// [`SystemTime`] instance to represent another fixed point in time. |
646 | /// |
647 | /// `duration_since(UNIX_EPOCH).unwrap().as_secs()` returns |
648 | /// the number of non-leap seconds since the start of 1970 UTC. |
649 | /// This is a POSIX `time_t` (as a `u64`), |
650 | /// and is the same time representation as used in many Internet protocols. |
651 | /// |
652 | /// # Examples |
653 | /// |
654 | /// ```no_run |
655 | /// use std::time::{SystemTime, UNIX_EPOCH}; |
656 | /// |
657 | /// match SystemTime::now().duration_since(UNIX_EPOCH) { |
658 | /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!" , n.as_secs()), |
659 | /// Err(_) => panic!("SystemTime before UNIX EPOCH!" ), |
660 | /// } |
661 | /// ``` |
662 | #[stable (feature = "time2" , since = "1.8.0" )] |
663 | pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH); |
664 | |
665 | impl SystemTimeError { |
666 | /// Returns the positive duration which represents how far forward the |
667 | /// second system time was from the first. |
668 | /// |
669 | /// A `SystemTimeError` is returned from the [`SystemTime::duration_since`] |
670 | /// and [`SystemTime::elapsed`] methods whenever the second system time |
671 | /// represents a point later in time than the `self` of the method call. |
672 | /// |
673 | /// # Examples |
674 | /// |
675 | /// ```no_run |
676 | /// use std::thread::sleep; |
677 | /// use std::time::{Duration, SystemTime}; |
678 | /// |
679 | /// let sys_time = SystemTime::now(); |
680 | /// sleep(Duration::from_secs(1)); |
681 | /// let new_sys_time = SystemTime::now(); |
682 | /// match sys_time.duration_since(new_sys_time) { |
683 | /// Ok(_) => {} |
684 | /// Err(e) => println!("SystemTimeError difference: {:?}" , e.duration()), |
685 | /// } |
686 | /// ``` |
687 | #[must_use ] |
688 | #[stable (feature = "time2" , since = "1.8.0" )] |
689 | pub fn duration(&self) -> Duration { |
690 | self.0 |
691 | } |
692 | } |
693 | |
694 | #[stable (feature = "time2" , since = "1.8.0" )] |
695 | impl Error for SystemTimeError { |
696 | #[allow (deprecated)] |
697 | fn description(&self) -> &str { |
698 | "other time was not earlier than self" |
699 | } |
700 | } |
701 | |
702 | #[stable (feature = "time2" , since = "1.8.0" )] |
703 | impl fmt::Display for SystemTimeError { |
704 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
705 | write!(f, "second time provided was later than self" ) |
706 | } |
707 | } |
708 | |
709 | impl FromInner<time::SystemTime> for SystemTime { |
710 | fn from_inner(time: time::SystemTime) -> SystemTime { |
711 | SystemTime(time) |
712 | } |
713 | } |
714 | |
715 | impl IntoInner<time::SystemTime> for SystemTime { |
716 | fn into_inner(self) -> time::SystemTime { |
717 | self.0 |
718 | } |
719 | } |
720 | |