1 //! Temporal quantification.
6 //! use std::time::Duration;
8 //! let five_seconds = Duration::new(5, 0);
9 //! // both declarations are equivalent
10 //! assert_eq!(Duration::new(5, 0), Duration::from_secs(5));
13 #![stable(feature = "time", since = "1.3.0")]
16 use crate::error::Error;
18 use crate::ops::{Add, AddAssign, Sub, SubAssign};
20 use crate::sys_common::mutex::Mutex;
21 use crate::sys_common::FromInner;
23 #[stable(feature = "time", since = "1.3.0")]
24 pub use core::time::Duration;
26 /// A measurement of a monotonically nondecreasing clock.
27 /// Opaque and useful only with `Duration`.
29 /// Instants are always guaranteed to be no less than any previously measured
30 /// instant when created, and are often useful for tasks such as measuring
31 /// benchmarks or timing how long an operation takes.
33 /// Note, however, that instants are not guaranteed to be **steady**. In other
34 /// words, each tick of the underlying clock may not be the same length (e.g.
35 /// some seconds may be longer than others). An instant may jump forwards or
36 /// experience time dilation (slow down or speed up), but it will never go
39 /// Instants are opaque types that can only be compared to one another. There is
40 /// no method to get "the number of seconds" from an instant. Instead, it only
41 /// allows measuring the duration between two instants (or comparing two
44 /// The size of an `Instant` struct may vary depending on the target operating
50 /// use std::time::{Duration, Instant};
51 /// use std::thread::sleep;
54 /// let now = Instant::now();
56 /// // we sleep for 2 seconds
57 /// sleep(Duration::new(2, 0));
59 /// println!("{}", now.elapsed().as_secs());
63 /// # OS-specific behaviors
65 /// An `Instant` is a wrapper around system-specific types and it may behave
66 /// differently depending on the underlying operating system. For example,
67 /// the following snippet is fine on Linux but panics on macOS:
70 /// use std::time::{Instant, Duration};
72 /// let now = Instant::now();
73 /// let max_nanoseconds = u64::MAX / 1_000_000_000;
74 /// let duration = Duration::new(max_nanoseconds, 0);
75 /// println!("{:?}", now + duration);
78 /// # Underlying System calls
79 /// Currently, the following system calls are being used to get the current time using `now()`:
81 /// | Platform | System call |
82 /// |:---------:|:--------------------------------------------------------------------:|
83 /// | CloudABI | [clock_time_get (Monotonic Clock)] |
84 /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
85 /// | UNIX | [clock_gettime (Monotonic Clock)] |
86 /// | Darwin | [mach_absolute_time] |
87 /// | VXWorks | [clock_gettime (Monotonic Clock)] |
88 /// | WASI | [__wasi_clock_time_get (Monotonic Clock)] |
89 /// | Windows | [QueryPerformanceCounter] |
91 /// [QueryPerformanceCounter]: https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter
92 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
93 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
94 /// [__wasi_clock_time_get (Monotonic Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
95 /// [clock_gettime (Monotonic Clock)]: https://linux.die.net/man/3/clock_gettime
96 /// [mach_absolute_time]: https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/KernelProgramming/services/services.html
97 /// [clock_time_get (Monotonic Clock)]: https://nuxi.nl/cloudabi/#clock_time_get
99 /// **Disclaimer:** These system calls might change over time.
101 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
102 #[stable(feature = "time2", since = "1.8.0")]
103 pub struct Instant(time::Instant);
105 /// A measurement of the system clock, useful for talking to
106 /// external entities like the file system or other processes.
108 /// Distinct from the [`Instant`] type, this time measurement **is not
109 /// monotonic**. This means that you can save a file to the file system, then
110 /// save another file to the file system, **and the second file has a
111 /// `SystemTime` measurement earlier than the first**. In other words, an
112 /// operation that happens after another operation in real time may have an
113 /// earlier `SystemTime`!
115 /// Consequently, comparing two `SystemTime` instances to learn about the
116 /// duration between them returns a [`Result`] instead of an infallible [`Duration`]
117 /// to indicate that this sort of time drift may happen and needs to be handled.
119 /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
120 /// constant is provided in this module as an anchor in time to learn
121 /// information about a `SystemTime`. By calculating the duration from this
122 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
123 /// or perhaps some other string representation.
125 /// The size of a `SystemTime` struct may vary depending on the target operating
128 /// [`Instant`]: ../../std/time/struct.Instant.html
129 /// [`Result`]: ../../std/result/enum.Result.html
130 /// [`Duration`]: ../../std/time/struct.Duration.html
131 /// [`UNIX_EPOCH`]: ../../std/time/constant.UNIX_EPOCH.html
136 /// use std::time::{Duration, SystemTime};
137 /// use std::thread::sleep;
140 /// let now = SystemTime::now();
142 /// // we sleep for 2 seconds
143 /// sleep(Duration::new(2, 0));
144 /// match now.elapsed() {
147 /// println!("{}", elapsed.as_secs());
150 /// // an error occurred!
151 /// println!("Error: {:?}", e);
157 /// # Underlying System calls
158 /// Currently, the following system calls are being used to get the current time using `now()`:
160 /// | Platform | System call |
161 /// |:---------:|:--------------------------------------------------------------------:|
162 /// | CloudABI | [clock_time_get (Realtime Clock)] |
163 /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
164 /// | UNIX | [clock_gettime (Realtime Clock)] |
165 /// | DARWIN | [gettimeofday] |
166 /// | VXWorks | [clock_gettime (Realtime Clock)] |
167 /// | WASI | [__wasi_clock_time_get (Realtime Clock)] |
168 /// | Windows | [GetSystemTimeAsFileTime] |
170 /// [clock_time_get (Realtime Clock)]: https://nuxi.nl/cloudabi/#clock_time_get
171 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
172 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
173 /// [gettimeofday]: http://man7.org/linux/man-pages/man2/gettimeofday.2.html
174 /// [clock_gettime (Realtime Clock)]: https://linux.die.net/man/3/clock_gettime
175 /// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
176 /// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime
178 /// **Disclaimer:** These system calls might change over time.
180 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
181 #[stable(feature = "time2", since = "1.8.0")]
182 pub struct SystemTime(time::SystemTime);
184 /// An error returned from the `duration_since` and `elapsed` methods on
185 /// `SystemTime`, used to learn how far in the opposite direction a system time
191 /// use std::thread::sleep;
192 /// use std::time::{Duration, SystemTime};
194 /// let sys_time = SystemTime::now();
195 /// sleep(Duration::from_secs(1));
196 /// let new_sys_time = SystemTime::now();
197 /// match sys_time.duration_since(new_sys_time) {
199 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
202 #[derive(Clone, Debug)]
203 #[stable(feature = "time2", since = "1.8.0")]
204 pub struct SystemTimeError(Duration);
207 /// Returns an instant corresponding to "now".
212 /// use std::time::Instant;
214 /// let now = Instant::now();
216 #[stable(feature = "time2", since = "1.8.0")]
217 pub fn now() -> Instant {
218 let os_now = time::Instant::now();
220 // And here we come upon a sad state of affairs. The whole point of
221 // `Instant` is that it's monotonically increasing. We've found in the
222 // wild, however, that it's not actually monotonically increasing for
223 // one reason or another. These appear to be OS and hardware level bugs,
224 // and there's not really a whole lot we can do about them. Here's a
225 // taste of what we've found:
227 // * #48514 - OpenBSD, x86_64
228 // * #49281 - linux arm64 and s390x
229 // * #51648 - windows, x86
230 // * #56560 - windows, x86_64, AWS
231 // * #56612 - windows, x86, vm (?)
232 // * #56940 - linux, arm64
233 // * https://bugzilla.mozilla.org/show_bug.cgi?id=1487778 - a similar
236 // It seems that this just happens a lot in the wild.
237 // We're seeing panics across various platforms where consecutive calls
238 // to `Instant::now`, such as via the `elapsed` function, are panicking
239 // as they're going backwards. Placed here is a last-ditch effort to try
240 // to fix things up. We keep a global "latest now" instance which is
241 // returned instead of what the OS says if the OS goes backwards.
243 // To hopefully mitigate the impact of this, a few platforms are
244 // whitelisted as "these at least haven't gone backwards yet".
245 if time::Instant::actually_monotonic() {
246 return Instant(os_now);
249 static LOCK: Mutex = Mutex::new();
250 static mut LAST_NOW: time::Instant = time::Instant::zero();
252 let _lock = LOCK.lock();
253 let now = cmp::max(LAST_NOW, os_now);
259 /// Returns the amount of time elapsed from another instant to this one.
263 /// This function will panic if `earlier` is later than `self`.
268 /// use std::time::{Duration, Instant};
269 /// use std::thread::sleep;
271 /// let now = Instant::now();
272 /// sleep(Duration::new(1, 0));
273 /// let new_now = Instant::now();
274 /// println!("{:?}", new_now.duration_since(now));
276 #[stable(feature = "time2", since = "1.8.0")]
277 pub fn duration_since(&self, earlier: Instant) -> Duration {
278 self.0.checked_sub_instant(&earlier.0).expect("supplied instant is later than self")
281 /// Returns the amount of time elapsed from another instant to this one,
282 /// or None if that instant is later than this one.
287 /// use std::time::{Duration, Instant};
288 /// use std::thread::sleep;
290 /// let now = Instant::now();
291 /// sleep(Duration::new(1, 0));
292 /// let new_now = Instant::now();
293 /// println!("{:?}", new_now.checked_duration_since(now));
294 /// println!("{:?}", now.checked_duration_since(new_now)); // None
296 #[stable(feature = "checked_duration_since", since = "1.39.0")]
297 pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
298 self.0.checked_sub_instant(&earlier.0)
301 /// Returns the amount of time elapsed from another instant to this one,
302 /// or zero duration if that instant is later than this one.
307 /// use std::time::{Duration, Instant};
308 /// use std::thread::sleep;
310 /// let now = Instant::now();
311 /// sleep(Duration::new(1, 0));
312 /// let new_now = Instant::now();
313 /// println!("{:?}", new_now.saturating_duration_since(now));
314 /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
316 #[stable(feature = "checked_duration_since", since = "1.39.0")]
317 pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
318 self.checked_duration_since(earlier).unwrap_or(Duration::new(0, 0))
321 /// Returns the amount of time elapsed since this instant was created.
325 /// This function may panic if the current time is earlier than this
326 /// instant, which is something that can happen if an `Instant` is
327 /// produced synthetically.
332 /// use std::thread::sleep;
333 /// use std::time::{Duration, Instant};
335 /// let instant = Instant::now();
336 /// let three_secs = Duration::from_secs(3);
337 /// sleep(three_secs);
338 /// assert!(instant.elapsed() >= three_secs);
340 #[stable(feature = "time2", since = "1.8.0")]
341 pub fn elapsed(&self) -> Duration {
342 Instant::now() - *self
345 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
346 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
348 #[stable(feature = "time_checked_add", since = "1.34.0")]
349 pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
350 self.0.checked_add_duration(&duration).map(Instant)
353 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
354 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
356 #[stable(feature = "time_checked_add", since = "1.34.0")]
357 pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
358 self.0.checked_sub_duration(&duration).map(Instant)
362 #[stable(feature = "time2", since = "1.8.0")]
363 impl Add<Duration> for Instant {
364 type Output = Instant;
368 /// This function may panic if the resulting point in time cannot be represented by the
369 /// underlying data structure. See [`checked_add`] for a version without panic.
371 /// [`checked_add`]: ../../std/time/struct.Instant.html#method.checked_add
372 fn add(self, other: Duration) -> Instant {
373 self.checked_add(other).expect("overflow when adding duration to instant")
377 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
378 impl AddAssign<Duration> for Instant {
379 fn add_assign(&mut self, other: Duration) {
380 *self = *self + other;
384 #[stable(feature = "time2", since = "1.8.0")]
385 impl Sub<Duration> for Instant {
386 type Output = Instant;
388 fn sub(self, other: Duration) -> Instant {
389 self.checked_sub(other).expect("overflow when subtracting duration from instant")
393 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
394 impl SubAssign<Duration> for Instant {
395 fn sub_assign(&mut self, other: Duration) {
396 *self = *self - other;
400 #[stable(feature = "time2", since = "1.8.0")]
401 impl Sub<Instant> for Instant {
402 type Output = Duration;
404 fn sub(self, other: Instant) -> Duration {
405 self.duration_since(other)
409 #[stable(feature = "time2", since = "1.8.0")]
410 impl fmt::Debug for Instant {
411 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417 /// An anchor in time which can be used to create new `SystemTime` instances or
418 /// learn about where in time a `SystemTime` lies.
420 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
421 /// respect to the system clock. Using `duration_since` on an existing
422 /// `SystemTime` instance can tell how far away from this point in time a
423 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
424 /// `SystemTime` instance to represent another fixed point in time.
429 /// use std::time::SystemTime;
431 /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
432 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
433 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
436 #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
437 pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
439 /// Returns the system time corresponding to "now".
444 /// use std::time::SystemTime;
446 /// let sys_time = SystemTime::now();
448 #[stable(feature = "time2", since = "1.8.0")]
449 pub fn now() -> SystemTime {
450 SystemTime(time::SystemTime::now())
453 /// Returns the amount of time elapsed from an earlier point in time.
455 /// This function may fail because measurements taken earlier are not
456 /// guaranteed to always be before later measurements (due to anomalies such
457 /// as the system clock being adjusted either forwards or backwards).
458 /// [`Instant`] can be used to measure elapsed time without this risk of failure.
460 /// If successful, [`Ok`]`(`[`Duration`]`)` is returned where the duration represents
461 /// the amount of time elapsed from the specified measurement to this one.
463 /// Returns an [`Err`] if `earlier` is later than `self`, and the error
464 /// contains how far from `self` the time is.
466 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
467 /// [`Duration`]: ../../std/time/struct.Duration.html
468 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
469 /// [`Instant`]: ../../std/time/struct.Instant.html
474 /// use std::time::SystemTime;
476 /// let sys_time = SystemTime::now();
477 /// let difference = sys_time.duration_since(sys_time)
478 /// .expect("Clock may have gone backwards");
479 /// println!("{:?}", difference);
481 #[stable(feature = "time2", since = "1.8.0")]
482 pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
483 self.0.sub_time(&earlier.0).map_err(SystemTimeError)
486 /// Returns the difference between the clock time when this
487 /// system time was created, and the current clock time.
489 /// This function may fail as the underlying system clock is susceptible to
490 /// drift and updates (e.g., the system clock could go backwards), so this
491 /// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is
492 /// returned where the duration represents the amount of time elapsed from
493 /// this time measurement to the current time.
495 /// To measure elapsed time reliably, use [`Instant`] instead.
497 /// Returns an [`Err`] if `self` is later than the current system time, and
498 /// the error contains how far from the current system time `self` is.
500 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
501 /// [`Duration`]: ../../std/time/struct.Duration.html
502 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
503 /// [`Instant`]: ../../std/time/struct.Instant.html
508 /// use std::thread::sleep;
509 /// use std::time::{Duration, SystemTime};
511 /// let sys_time = SystemTime::now();
512 /// let one_sec = Duration::from_secs(1);
514 /// assert!(sys_time.elapsed().unwrap() >= one_sec);
516 #[stable(feature = "time2", since = "1.8.0")]
517 pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
518 SystemTime::now().duration_since(*self)
521 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
522 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
524 #[stable(feature = "time_checked_add", since = "1.34.0")]
525 pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
526 self.0.checked_add_duration(&duration).map(SystemTime)
529 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
530 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
532 #[stable(feature = "time_checked_add", since = "1.34.0")]
533 pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
534 self.0.checked_sub_duration(&duration).map(SystemTime)
538 #[stable(feature = "time2", since = "1.8.0")]
539 impl Add<Duration> for SystemTime {
540 type Output = SystemTime;
544 /// This function may panic if the resulting point in time cannot be represented by the
545 /// underlying data structure. See [`checked_add`] for a version without panic.
547 /// [`checked_add`]: ../../std/time/struct.SystemTime.html#method.checked_add
548 fn add(self, dur: Duration) -> SystemTime {
549 self.checked_add(dur).expect("overflow when adding duration to instant")
553 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
554 impl AddAssign<Duration> for SystemTime {
555 fn add_assign(&mut self, other: Duration) {
556 *self = *self + other;
560 #[stable(feature = "time2", since = "1.8.0")]
561 impl Sub<Duration> for SystemTime {
562 type Output = SystemTime;
564 fn sub(self, dur: Duration) -> SystemTime {
565 self.checked_sub(dur).expect("overflow when subtracting duration from instant")
569 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
570 impl SubAssign<Duration> for SystemTime {
571 fn sub_assign(&mut self, other: Duration) {
572 *self = *self - other;
576 #[stable(feature = "time2", since = "1.8.0")]
577 impl fmt::Debug for SystemTime {
578 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
583 /// An anchor in time which can be used to create new `SystemTime` instances or
584 /// learn about where in time a `SystemTime` lies.
586 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
587 /// respect to the system clock. Using `duration_since` on an existing
588 /// [`SystemTime`] instance can tell how far away from this point in time a
589 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
590 /// [`SystemTime`] instance to represent another fixed point in time.
592 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
597 /// use std::time::{SystemTime, UNIX_EPOCH};
599 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
600 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
601 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
604 #[stable(feature = "time2", since = "1.8.0")]
605 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
607 impl SystemTimeError {
608 /// Returns the positive duration which represents how far forward the
609 /// second system time was from the first.
611 /// A `SystemTimeError` is returned from the [`duration_since`] and [`elapsed`]
612 /// methods of [`SystemTime`] whenever the second system time represents a point later
613 /// in time than the `self` of the method call.
615 /// [`duration_since`]: ../../std/time/struct.SystemTime.html#method.duration_since
616 /// [`elapsed`]: ../../std/time/struct.SystemTime.html#method.elapsed
617 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
622 /// use std::thread::sleep;
623 /// use std::time::{Duration, SystemTime};
625 /// let sys_time = SystemTime::now();
626 /// sleep(Duration::from_secs(1));
627 /// let new_sys_time = SystemTime::now();
628 /// match sys_time.duration_since(new_sys_time) {
630 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
633 #[stable(feature = "time2", since = "1.8.0")]
634 pub fn duration(&self) -> Duration {
639 #[stable(feature = "time2", since = "1.8.0")]
640 impl Error for SystemTimeError {
642 fn description(&self) -> &str {
643 "other time was not earlier than self"
647 #[stable(feature = "time2", since = "1.8.0")]
648 impl fmt::Display for SystemTimeError {
649 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
650 write!(f, "second time provided was later than self")
654 impl FromInner<time::SystemTime> for SystemTime {
655 fn from_inner(time: time::SystemTime) -> SystemTime {
662 use super::{Duration, Instant, SystemTime, UNIX_EPOCH};
664 macro_rules! assert_almost_eq {
665 ($a:expr, $b:expr) => {{
666 let (a, b) = ($a, $b);
668 let (a, b) = if a > b { (a, b) } else { (b, a) };
669 assert!(a - Duration::new(0, 1000) <= b, "{:?} is not almost equal to {:?}", a, b);
675 fn instant_monotonic() {
676 let a = Instant::now();
677 let b = Instant::now();
682 fn instant_elapsed() {
683 let a = Instant::now();
689 let a = Instant::now();
690 let b = Instant::now();
691 println!("a: {:?}", a);
692 println!("b: {:?}", b);
693 let dur = b.duration_since(a);
694 println!("dur: {:?}", dur);
695 assert_almost_eq!(b - dur, a);
696 assert_almost_eq!(a + dur, b);
698 let second = Duration::new(1, 0);
699 assert_almost_eq!(a - second + second, a);
700 assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a);
702 // checked_add_duration will not panic on overflow
703 let mut maybe_t = Some(Instant::now());
704 let max_duration = Duration::from_secs(u64::max_value());
705 // in case `Instant` can store `>= now + max_duration`.
707 maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
709 assert_eq!(maybe_t, None);
711 // checked_add_duration calculates the right time and will work for another year
712 let year = Duration::from_secs(60 * 60 * 24 * 365);
713 assert_eq!(a + year, a.checked_add(year).unwrap());
717 fn instant_math_is_associative() {
718 let now = Instant::now();
719 let offset = Duration::from_millis(5);
720 // Changing the order of instant math shouldn't change the results,
721 // especially when the expression reduces to X + identity.
722 assert_eq!((now + offset) - now, (now - now) + offset);
727 fn instant_duration_since_panic() {
728 let a = Instant::now();
729 (a - Duration::new(1, 0)).duration_since(a);
733 fn instant_checked_duration_since_nopanic() {
734 let now = Instant::now();
735 let earlier = now - Duration::new(1, 0);
736 let later = now + Duration::new(1, 0);
737 assert_eq!(earlier.checked_duration_since(now), None);
738 assert_eq!(later.checked_duration_since(now), Some(Duration::new(1, 0)));
739 assert_eq!(now.checked_duration_since(now), Some(Duration::new(0, 0)));
743 fn instant_saturating_duration_since_nopanic() {
744 let a = Instant::now();
745 let ret = (a - Duration::new(1, 0)).saturating_duration_since(a);
746 assert_eq!(ret, Duration::new(0, 0));
750 fn system_time_math() {
751 let a = SystemTime::now();
752 let b = SystemTime::now();
753 match b.duration_since(a) {
754 Ok(dur) if dur == Duration::new(0, 0) => {
755 assert_almost_eq!(a, b);
759 assert_almost_eq!(b - dur, a);
760 assert_almost_eq!(a + dur, b);
763 let dur = dur.duration();
765 assert_almost_eq!(b + dur, a);
766 assert_almost_eq!(a - dur, b);
770 let second = Duration::new(1, 0);
771 assert_almost_eq!(a.duration_since(a - second).unwrap(), second);
772 assert_almost_eq!(a.duration_since(a + second).unwrap_err().duration(), second);
774 assert_almost_eq!(a - second + second, a);
775 assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a);
777 let one_second_from_epoch = UNIX_EPOCH + Duration::new(1, 0);
778 let one_second_from_epoch2 =
779 UNIX_EPOCH + Duration::new(0, 500_000_000) + Duration::new(0, 500_000_000);
780 assert_eq!(one_second_from_epoch, one_second_from_epoch2);
782 // checked_add_duration will not panic on overflow
783 let mut maybe_t = Some(SystemTime::UNIX_EPOCH);
784 let max_duration = Duration::from_secs(u64::max_value());
785 // in case `SystemTime` can store `>= UNIX_EPOCH + max_duration`.
787 maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
789 assert_eq!(maybe_t, None);
791 // checked_add_duration calculates the right time and will work for another year
792 let year = Duration::from_secs(60 * 60 * 24 * 365);
793 assert_eq!(a + year, a.checked_add(year).unwrap());
797 fn system_time_elapsed() {
798 let a = SystemTime::now();
804 let ts = SystemTime::now();
805 let a = ts.duration_since(UNIX_EPOCH + Duration::new(1, 0)).unwrap();
806 let b = ts.duration_since(UNIX_EPOCH).unwrap();
808 assert_eq!(b - a, Duration::new(1, 0));
810 let thirty_years = Duration::new(1, 0) * 60 * 60 * 24 * 365 * 30;
812 // Right now for CI this test is run in an emulator, and apparently the
813 // aarch64 emulator's sense of time is that we're still living in the
816 // Otherwise let's assume that we're all running computers later than
818 if !cfg!(target_arch = "aarch64") {
819 assert!(a > thirty_years);
822 // let's assume that we're all running computers earlier than 2090.
823 // Should give us ~70 years to fix this!
824 let hundred_twenty_years = thirty_years * 4;
825 assert!(a < hundred_twenty_years);