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")]
19 use crate::error::Error;
21 use crate::ops::{Add, AddAssign, Sub, SubAssign};
23 use crate::sys_common::mutex::StaticMutex;
24 use crate::sys_common::FromInner;
26 #[stable(feature = "time", since = "1.3.0")]
27 pub use core::time::Duration;
29 /// A measurement of a monotonically nondecreasing clock.
30 /// Opaque and useful only with `Duration`.
32 /// Instants are always guaranteed to be no less than any previously measured
33 /// instant when created, and are often useful for tasks such as measuring
34 /// benchmarks or timing how long an operation takes.
36 /// Note, however, that instants are not guaranteed to be **steady**. In other
37 /// words, each tick of the underlying clock may not be the same length (e.g.
38 /// some seconds may be longer than others). An instant may jump forwards or
39 /// experience time dilation (slow down or speed up), but it will never go
42 /// Instants are opaque types that can only be compared to one another. There is
43 /// no method to get "the number of seconds" from an instant. Instead, it only
44 /// allows measuring the duration between two instants (or comparing two
47 /// The size of an `Instant` struct may vary depending on the target operating
53 /// use std::time::{Duration, Instant};
54 /// use std::thread::sleep;
57 /// let now = Instant::now();
59 /// // we sleep for 2 seconds
60 /// sleep(Duration::new(2, 0));
62 /// println!("{}", now.elapsed().as_secs());
66 /// # OS-specific behaviors
68 /// An `Instant` is a wrapper around system-specific types and it may behave
69 /// differently depending on the underlying operating system. For example,
70 /// the following snippet is fine on Linux but panics on macOS:
73 /// use std::time::{Instant, Duration};
75 /// let now = Instant::now();
76 /// let max_nanoseconds = u64::MAX / 1_000_000_000;
77 /// let duration = Duration::new(max_nanoseconds, 0);
78 /// println!("{:?}", now + duration);
81 /// # Underlying System calls
82 /// Currently, the following system calls are being used to get the current time using `now()`:
84 /// | Platform | System call |
85 /// |:---------:|:--------------------------------------------------------------------:|
86 /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
87 /// | UNIX | [clock_gettime (Monotonic Clock)] |
88 /// | Darwin | [mach_absolute_time] |
89 /// | VXWorks | [clock_gettime (Monotonic Clock)] |
90 /// | WASI | [__wasi_clock_time_get (Monotonic Clock)] |
91 /// | Windows | [QueryPerformanceCounter] |
93 /// [QueryPerformanceCounter]: https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter
94 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
95 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
96 /// [__wasi_clock_time_get (Monotonic Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
97 /// [clock_gettime (Monotonic Clock)]: https://linux.die.net/man/3/clock_gettime
98 /// [mach_absolute_time]: https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/KernelProgramming/services/services.html
100 /// **Disclaimer:** These system calls might change over time.
102 /// > Note: mathematical operations like [`add`] may panic if the underlying
103 /// > structure cannot represent the new point in time.
105 /// [`add`]: Instant::add
106 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
107 #[stable(feature = "time2", since = "1.8.0")]
108 pub struct Instant(time::Instant);
110 /// A measurement of the system clock, useful for talking to
111 /// external entities like the file system or other processes.
113 /// Distinct from the [`Instant`] type, this time measurement **is not
114 /// monotonic**. This means that you can save a file to the file system, then
115 /// save another file to the file system, **and the second file has a
116 /// `SystemTime` measurement earlier than the first**. In other words, an
117 /// operation that happens after another operation in real time may have an
118 /// earlier `SystemTime`!
120 /// Consequently, comparing two `SystemTime` instances to learn about the
121 /// duration between them returns a [`Result`] instead of an infallible [`Duration`]
122 /// to indicate that this sort of time drift may happen and needs to be handled.
124 /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
125 /// constant is provided in this module as an anchor in time to learn
126 /// information about a `SystemTime`. By calculating the duration from this
127 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
128 /// or perhaps some other string representation.
130 /// The size of a `SystemTime` struct may vary depending on the target operating
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 /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
163 /// | UNIX | [clock_gettime (Realtime Clock)] |
164 /// | Darwin | [gettimeofday] |
165 /// | VXWorks | [clock_gettime (Realtime Clock)] |
166 /// | WASI | [__wasi_clock_time_get (Realtime Clock)] |
167 /// | Windows | [GetSystemTimePreciseAsFileTime] / [GetSystemTimeAsFileTime] |
169 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
170 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
171 /// [gettimeofday]: http://man7.org/linux/man-pages/man2/gettimeofday.2.html
172 /// [clock_gettime (Realtime Clock)]: https://linux.die.net/man/3/clock_gettime
173 /// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
174 /// [GetSystemTimePreciseAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
175 /// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime
177 /// **Disclaimer:** These system calls might change over time.
179 /// > Note: mathematical operations like [`add`] may panic if the underlying
180 /// > structure cannot represent the new point in time.
182 /// [`add`]: SystemTime::add
183 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
184 #[stable(feature = "time2", since = "1.8.0")]
185 pub struct SystemTime(time::SystemTime);
187 /// An error returned from the `duration_since` and `elapsed` methods on
188 /// `SystemTime`, used to learn how far in the opposite direction a system time
194 /// use std::thread::sleep;
195 /// use std::time::{Duration, SystemTime};
197 /// let sys_time = SystemTime::now();
198 /// sleep(Duration::from_secs(1));
199 /// let new_sys_time = SystemTime::now();
200 /// match sys_time.duration_since(new_sys_time) {
202 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
205 #[derive(Clone, Debug)]
206 #[stable(feature = "time2", since = "1.8.0")]
207 pub struct SystemTimeError(Duration);
210 /// Returns an instant corresponding to "now".
215 /// use std::time::Instant;
217 /// let now = Instant::now();
219 #[stable(feature = "time2", since = "1.8.0")]
220 pub fn now() -> Instant {
221 let os_now = time::Instant::now();
223 // And here we come upon a sad state of affairs. The whole point of
224 // `Instant` is that it's monotonically increasing. We've found in the
225 // wild, however, that it's not actually monotonically increasing for
226 // one reason or another. These appear to be OS and hardware level bugs,
227 // and there's not really a whole lot we can do about them. Here's a
228 // taste of what we've found:
230 // * #48514 - OpenBSD, x86_64
231 // * #49281 - linux arm64 and s390x
232 // * #51648 - windows, x86
233 // * #56560 - windows, x86_64, AWS
234 // * #56612 - windows, x86, vm (?)
235 // * #56940 - linux, arm64
236 // * https://bugzilla.mozilla.org/show_bug.cgi?id=1487778 - a similar
239 // It seems that this just happens a lot in the wild.
240 // We're seeing panics across various platforms where consecutive calls
241 // to `Instant::now`, such as via the `elapsed` function, are panicking
242 // as they're going backwards. Placed here is a last-ditch effort to try
243 // to fix things up. We keep a global "latest now" instance which is
244 // returned instead of what the OS says if the OS goes backwards.
246 // To hopefully mitigate the impact of this, a few platforms are
247 // excluded as "these at least haven't gone backwards yet".
248 if time::Instant::actually_monotonic() {
249 return Instant(os_now);
252 static LOCK: StaticMutex = StaticMutex::new();
253 static mut LAST_NOW: time::Instant = time::Instant::zero();
255 let _lock = LOCK.lock();
256 let now = cmp::max(LAST_NOW, os_now);
262 /// Returns the amount of time elapsed from another instant to this one.
266 /// This function will panic if `earlier` is later than `self`.
271 /// use std::time::{Duration, Instant};
272 /// use std::thread::sleep;
274 /// let now = Instant::now();
275 /// sleep(Duration::new(1, 0));
276 /// let new_now = Instant::now();
277 /// println!("{:?}", new_now.duration_since(now));
279 #[stable(feature = "time2", since = "1.8.0")]
280 pub fn duration_since(&self, earlier: Instant) -> Duration {
281 self.0.checked_sub_instant(&earlier.0).expect("supplied instant is later than self")
284 /// Returns the amount of time elapsed from another instant to this one,
285 /// or None if that instant is later than this one.
290 /// use std::time::{Duration, Instant};
291 /// use std::thread::sleep;
293 /// let now = Instant::now();
294 /// sleep(Duration::new(1, 0));
295 /// let new_now = Instant::now();
296 /// println!("{:?}", new_now.checked_duration_since(now));
297 /// println!("{:?}", now.checked_duration_since(new_now)); // None
299 #[stable(feature = "checked_duration_since", since = "1.39.0")]
300 pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
301 self.0.checked_sub_instant(&earlier.0)
304 /// Returns the amount of time elapsed from another instant to this one,
305 /// or zero duration if that instant is later than this one.
310 /// use std::time::{Duration, Instant};
311 /// use std::thread::sleep;
313 /// let now = Instant::now();
314 /// sleep(Duration::new(1, 0));
315 /// let new_now = Instant::now();
316 /// println!("{:?}", new_now.saturating_duration_since(now));
317 /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
319 #[stable(feature = "checked_duration_since", since = "1.39.0")]
320 pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
321 self.checked_duration_since(earlier).unwrap_or_default()
324 /// Returns the amount of time elapsed since this instant was created.
328 /// This function may panic if the current time is earlier than this
329 /// instant, which is something that can happen if an `Instant` is
330 /// produced synthetically.
335 /// use std::thread::sleep;
336 /// use std::time::{Duration, Instant};
338 /// let instant = Instant::now();
339 /// let three_secs = Duration::from_secs(3);
340 /// sleep(three_secs);
341 /// assert!(instant.elapsed() >= three_secs);
343 #[stable(feature = "time2", since = "1.8.0")]
344 pub fn elapsed(&self) -> Duration {
345 Instant::now() - *self
348 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
349 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
351 #[stable(feature = "time_checked_add", since = "1.34.0")]
352 pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
353 self.0.checked_add_duration(&duration).map(Instant)
356 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
357 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
359 #[stable(feature = "time_checked_add", since = "1.34.0")]
360 pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
361 self.0.checked_sub_duration(&duration).map(Instant)
365 #[stable(feature = "time2", since = "1.8.0")]
366 impl Add<Duration> for Instant {
367 type Output = Instant;
371 /// This function may panic if the resulting point in time cannot be represented by the
372 /// underlying data structure. See [`Instant::checked_add`] for a version without panic.
373 fn add(self, other: Duration) -> Instant {
374 self.checked_add(other).expect("overflow when adding duration to instant")
378 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
379 impl AddAssign<Duration> for Instant {
380 fn add_assign(&mut self, other: Duration) {
381 *self = *self + other;
385 #[stable(feature = "time2", since = "1.8.0")]
386 impl Sub<Duration> for Instant {
387 type Output = Instant;
389 fn sub(self, other: Duration) -> Instant {
390 self.checked_sub(other).expect("overflow when subtracting duration from instant")
394 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
395 impl SubAssign<Duration> for Instant {
396 fn sub_assign(&mut self, other: Duration) {
397 *self = *self - other;
401 #[stable(feature = "time2", since = "1.8.0")]
402 impl Sub<Instant> for Instant {
403 type Output = Duration;
405 fn sub(self, other: Instant) -> Duration {
406 self.duration_since(other)
410 #[stable(feature = "time2", since = "1.8.0")]
411 impl fmt::Debug for Instant {
412 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
418 /// An anchor in time which can be used to create new `SystemTime` instances or
419 /// learn about where in time a `SystemTime` lies.
421 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
422 /// respect to the system clock. Using `duration_since` on an existing
423 /// `SystemTime` instance can tell how far away from this point in time a
424 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
425 /// `SystemTime` instance to represent another fixed point in time.
430 /// use std::time::SystemTime;
432 /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
433 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
434 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
437 #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
438 pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
440 /// Returns the system time corresponding to "now".
445 /// use std::time::SystemTime;
447 /// let sys_time = SystemTime::now();
449 #[stable(feature = "time2", since = "1.8.0")]
450 pub fn now() -> SystemTime {
451 SystemTime(time::SystemTime::now())
454 /// Returns the amount of time elapsed from an earlier point in time.
456 /// This function may fail because measurements taken earlier are not
457 /// guaranteed to always be before later measurements (due to anomalies such
458 /// as the system clock being adjusted either forwards or backwards).
459 /// [`Instant`] can be used to measure elapsed time without this risk of failure.
461 /// If successful, [`Ok`]`(`[`Duration`]`)` is returned where the duration represents
462 /// the amount of time elapsed from the specified measurement to this one.
464 /// Returns an [`Err`] if `earlier` is later than `self`, and the error
465 /// contains how far from `self` the time is.
470 /// use std::time::SystemTime;
472 /// let sys_time = SystemTime::now();
473 /// let new_sys_time = SystemTime::now();
474 /// let difference = new_sys_time.duration_since(sys_time)
475 /// .expect("Clock may have gone backwards");
476 /// println!("{:?}", difference);
478 #[stable(feature = "time2", since = "1.8.0")]
479 pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
480 self.0.sub_time(&earlier.0).map_err(SystemTimeError)
483 /// Returns the difference between the clock time when this
484 /// system time was created, and the current clock time.
486 /// This function may fail as the underlying system clock is susceptible to
487 /// drift and updates (e.g., the system clock could go backwards), so this
488 /// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is
489 /// returned where the duration represents the amount of time elapsed from
490 /// this time measurement to the current time.
492 /// To measure elapsed time reliably, use [`Instant`] instead.
494 /// Returns an [`Err`] if `self` is later than the current system time, and
495 /// the error contains how far from the current system time `self` is.
500 /// use std::thread::sleep;
501 /// use std::time::{Duration, SystemTime};
503 /// let sys_time = SystemTime::now();
504 /// let one_sec = Duration::from_secs(1);
506 /// assert!(sys_time.elapsed().unwrap() >= one_sec);
508 #[stable(feature = "time2", since = "1.8.0")]
509 pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
510 SystemTime::now().duration_since(*self)
513 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
514 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
516 #[stable(feature = "time_checked_add", since = "1.34.0")]
517 pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
518 self.0.checked_add_duration(&duration).map(SystemTime)
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_sub(&self, duration: Duration) -> Option<SystemTime> {
526 self.0.checked_sub_duration(&duration).map(SystemTime)
530 #[stable(feature = "time2", since = "1.8.0")]
531 impl Add<Duration> for SystemTime {
532 type Output = SystemTime;
536 /// This function may panic if the resulting point in time cannot be represented by the
537 /// underlying data structure. See [`SystemTime::checked_add`] for a version without panic.
538 fn add(self, dur: Duration) -> SystemTime {
539 self.checked_add(dur).expect("overflow when adding duration to instant")
543 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
544 impl AddAssign<Duration> for SystemTime {
545 fn add_assign(&mut self, other: Duration) {
546 *self = *self + other;
550 #[stable(feature = "time2", since = "1.8.0")]
551 impl Sub<Duration> for SystemTime {
552 type Output = SystemTime;
554 fn sub(self, dur: Duration) -> SystemTime {
555 self.checked_sub(dur).expect("overflow when subtracting duration from instant")
559 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
560 impl SubAssign<Duration> for SystemTime {
561 fn sub_assign(&mut self, other: Duration) {
562 *self = *self - other;
566 #[stable(feature = "time2", since = "1.8.0")]
567 impl fmt::Debug for SystemTime {
568 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
573 /// An anchor in time which can be used to create new `SystemTime` instances or
574 /// learn about where in time a `SystemTime` lies.
576 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
577 /// respect to the system clock. Using `duration_since` on an existing
578 /// [`SystemTime`] instance can tell how far away from this point in time a
579 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
580 /// [`SystemTime`] instance to represent another fixed point in time.
585 /// use std::time::{SystemTime, UNIX_EPOCH};
587 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
588 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
589 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
592 #[stable(feature = "time2", since = "1.8.0")]
593 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
595 impl SystemTimeError {
596 /// Returns the positive duration which represents how far forward the
597 /// second system time was from the first.
599 /// A `SystemTimeError` is returned from the [`SystemTime::duration_since`]
600 /// and [`SystemTime::elapsed`] methods whenever the second system time
601 /// represents a point later in time than the `self` of the method call.
606 /// use std::thread::sleep;
607 /// use std::time::{Duration, SystemTime};
609 /// let sys_time = SystemTime::now();
610 /// sleep(Duration::from_secs(1));
611 /// let new_sys_time = SystemTime::now();
612 /// match sys_time.duration_since(new_sys_time) {
614 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
617 #[stable(feature = "time2", since = "1.8.0")]
618 pub fn duration(&self) -> Duration {
623 #[stable(feature = "time2", since = "1.8.0")]
624 impl Error for SystemTimeError {
626 fn description(&self) -> &str {
627 "other time was not earlier than self"
631 #[stable(feature = "time2", since = "1.8.0")]
632 impl fmt::Display for SystemTimeError {
633 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
634 write!(f, "second time provided was later than self")
638 impl FromInner<time::SystemTime> for SystemTime {
639 fn from_inner(time: time::SystemTime) -> SystemTime {