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 /// | CloudABI | [clock_time_get (Monotonic Clock)] |
87 /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
88 /// | UNIX | [clock_gettime (Monotonic Clock)] |
89 /// | Darwin | [mach_absolute_time] |
90 /// | VXWorks | [clock_gettime (Monotonic Clock)] |
91 /// | WASI | [__wasi_clock_time_get (Monotonic Clock)] |
92 /// | Windows | [QueryPerformanceCounter] |
94 /// [QueryPerformanceCounter]: https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter
95 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
96 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
97 /// [__wasi_clock_time_get (Monotonic Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
98 /// [clock_gettime (Monotonic Clock)]: https://linux.die.net/man/3/clock_gettime
99 /// [mach_absolute_time]: https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/KernelProgramming/services/services.html
100 /// [clock_time_get (Monotonic Clock)]: https://nuxi.nl/cloudabi/#clock_time_get
102 /// **Disclaimer:** These system calls might change over time.
104 /// > Note: mathematical operations like [`add`] may panic if the underlying
105 /// > structure cannot represent the new point in time.
107 /// [`add`]: Instant::add
108 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
109 #[stable(feature = "time2", since = "1.8.0")]
110 pub struct Instant(time::Instant);
112 /// A measurement of the system clock, useful for talking to
113 /// external entities like the file system or other processes.
115 /// Distinct from the [`Instant`] type, this time measurement **is not
116 /// monotonic**. This means that you can save a file to the file system, then
117 /// save another file to the file system, **and the second file has a
118 /// `SystemTime` measurement earlier than the first**. In other words, an
119 /// operation that happens after another operation in real time may have an
120 /// earlier `SystemTime`!
122 /// Consequently, comparing two `SystemTime` instances to learn about the
123 /// duration between them returns a [`Result`] instead of an infallible [`Duration`]
124 /// to indicate that this sort of time drift may happen and needs to be handled.
126 /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
127 /// constant is provided in this module as an anchor in time to learn
128 /// information about a `SystemTime`. By calculating the duration from this
129 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
130 /// or perhaps some other string representation.
132 /// The size of a `SystemTime` struct may vary depending on the target operating
138 /// use std::time::{Duration, SystemTime};
139 /// use std::thread::sleep;
142 /// let now = SystemTime::now();
144 /// // we sleep for 2 seconds
145 /// sleep(Duration::new(2, 0));
146 /// match now.elapsed() {
149 /// println!("{}", elapsed.as_secs());
152 /// // an error occurred!
153 /// println!("Error: {:?}", e);
159 /// # Underlying System calls
160 /// Currently, the following system calls are being used to get the current time using `now()`:
162 /// | Platform | System call |
163 /// |:---------:|:--------------------------------------------------------------------:|
164 /// | CloudABI | [clock_time_get (Realtime Clock)] |
165 /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
166 /// | UNIX | [clock_gettime (Realtime Clock)] |
167 /// | Darwin | [gettimeofday] |
168 /// | VXWorks | [clock_gettime (Realtime Clock)] |
169 /// | WASI | [__wasi_clock_time_get (Realtime Clock)] |
170 /// | Windows | [GetSystemTimePreciseAsFileTime] / [GetSystemTimeAsFileTime] |
172 /// [clock_time_get (Realtime Clock)]: https://nuxi.nl/cloudabi/#clock_time_get
173 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
174 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
175 /// [gettimeofday]: http://man7.org/linux/man-pages/man2/gettimeofday.2.html
176 /// [clock_gettime (Realtime Clock)]: https://linux.die.net/man/3/clock_gettime
177 /// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
178 /// [GetSystemTimePreciseAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
179 /// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime
181 /// **Disclaimer:** These system calls might change over time.
183 /// > Note: mathematical operations like [`add`] may panic if the underlying
184 /// > structure cannot represent the new point in time.
186 /// [`add`]: SystemTime::add
187 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
188 #[stable(feature = "time2", since = "1.8.0")]
189 pub struct SystemTime(time::SystemTime);
191 /// An error returned from the `duration_since` and `elapsed` methods on
192 /// `SystemTime`, used to learn how far in the opposite direction a system time
198 /// use std::thread::sleep;
199 /// use std::time::{Duration, SystemTime};
201 /// let sys_time = SystemTime::now();
202 /// sleep(Duration::from_secs(1));
203 /// let new_sys_time = SystemTime::now();
204 /// match sys_time.duration_since(new_sys_time) {
206 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
209 #[derive(Clone, Debug)]
210 #[stable(feature = "time2", since = "1.8.0")]
211 pub struct SystemTimeError(Duration);
214 /// Returns an instant corresponding to "now".
219 /// use std::time::Instant;
221 /// let now = Instant::now();
223 #[stable(feature = "time2", since = "1.8.0")]
224 pub fn now() -> Instant {
225 let os_now = time::Instant::now();
227 // And here we come upon a sad state of affairs. The whole point of
228 // `Instant` is that it's monotonically increasing. We've found in the
229 // wild, however, that it's not actually monotonically increasing for
230 // one reason or another. These appear to be OS and hardware level bugs,
231 // and there's not really a whole lot we can do about them. Here's a
232 // taste of what we've found:
234 // * #48514 - OpenBSD, x86_64
235 // * #49281 - linux arm64 and s390x
236 // * #51648 - windows, x86
237 // * #56560 - windows, x86_64, AWS
238 // * #56612 - windows, x86, vm (?)
239 // * #56940 - linux, arm64
240 // * https://bugzilla.mozilla.org/show_bug.cgi?id=1487778 - a similar
243 // It seems that this just happens a lot in the wild.
244 // We're seeing panics across various platforms where consecutive calls
245 // to `Instant::now`, such as via the `elapsed` function, are panicking
246 // as they're going backwards. Placed here is a last-ditch effort to try
247 // to fix things up. We keep a global "latest now" instance which is
248 // returned instead of what the OS says if the OS goes backwards.
250 // To hopefully mitigate the impact of this, a few platforms are
251 // excluded as "these at least haven't gone backwards yet".
252 if time::Instant::actually_monotonic() {
253 return Instant(os_now);
256 static LOCK: StaticMutex = StaticMutex::new();
257 static mut LAST_NOW: time::Instant = time::Instant::zero();
259 let _lock = LOCK.lock();
260 let now = cmp::max(LAST_NOW, os_now);
266 /// Returns the amount of time elapsed from another instant to this one.
270 /// This function will panic if `earlier` is later than `self`.
275 /// use std::time::{Duration, Instant};
276 /// use std::thread::sleep;
278 /// let now = Instant::now();
279 /// sleep(Duration::new(1, 0));
280 /// let new_now = Instant::now();
281 /// println!("{:?}", new_now.duration_since(now));
283 #[stable(feature = "time2", since = "1.8.0")]
284 pub fn duration_since(&self, earlier: Instant) -> Duration {
285 self.0.checked_sub_instant(&earlier.0).expect("supplied instant is later than self")
288 /// Returns the amount of time elapsed from another instant to this one,
289 /// or None if that instant is later than this one.
294 /// use std::time::{Duration, Instant};
295 /// use std::thread::sleep;
297 /// let now = Instant::now();
298 /// sleep(Duration::new(1, 0));
299 /// let new_now = Instant::now();
300 /// println!("{:?}", new_now.checked_duration_since(now));
301 /// println!("{:?}", now.checked_duration_since(new_now)); // None
303 #[stable(feature = "checked_duration_since", since = "1.39.0")]
304 pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
305 self.0.checked_sub_instant(&earlier.0)
308 /// Returns the amount of time elapsed from another instant to this one,
309 /// or zero duration if that instant is later than this one.
314 /// use std::time::{Duration, Instant};
315 /// use std::thread::sleep;
317 /// let now = Instant::now();
318 /// sleep(Duration::new(1, 0));
319 /// let new_now = Instant::now();
320 /// println!("{:?}", new_now.saturating_duration_since(now));
321 /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
323 #[stable(feature = "checked_duration_since", since = "1.39.0")]
324 pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
325 self.checked_duration_since(earlier).unwrap_or_default()
328 /// Returns the amount of time elapsed since this instant was created.
332 /// This function may panic if the current time is earlier than this
333 /// instant, which is something that can happen if an `Instant` is
334 /// produced synthetically.
339 /// use std::thread::sleep;
340 /// use std::time::{Duration, Instant};
342 /// let instant = Instant::now();
343 /// let three_secs = Duration::from_secs(3);
344 /// sleep(three_secs);
345 /// assert!(instant.elapsed() >= three_secs);
347 #[stable(feature = "time2", since = "1.8.0")]
348 pub fn elapsed(&self) -> Duration {
349 Instant::now() - *self
352 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
353 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
355 #[stable(feature = "time_checked_add", since = "1.34.0")]
356 pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
357 self.0.checked_add_duration(&duration).map(Instant)
360 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
361 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
363 #[stable(feature = "time_checked_add", since = "1.34.0")]
364 pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
365 self.0.checked_sub_duration(&duration).map(Instant)
369 #[stable(feature = "time2", since = "1.8.0")]
370 impl Add<Duration> for Instant {
371 type Output = Instant;
375 /// This function may panic if the resulting point in time cannot be represented by the
376 /// underlying data structure. See [`Instant::checked_add`] for a version without panic.
377 fn add(self, other: Duration) -> Instant {
378 self.checked_add(other).expect("overflow when adding duration to instant")
382 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
383 impl AddAssign<Duration> for Instant {
384 fn add_assign(&mut self, other: Duration) {
385 *self = *self + other;
389 #[stable(feature = "time2", since = "1.8.0")]
390 impl Sub<Duration> for Instant {
391 type Output = Instant;
393 fn sub(self, other: Duration) -> Instant {
394 self.checked_sub(other).expect("overflow when subtracting duration from instant")
398 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
399 impl SubAssign<Duration> for Instant {
400 fn sub_assign(&mut self, other: Duration) {
401 *self = *self - other;
405 #[stable(feature = "time2", since = "1.8.0")]
406 impl Sub<Instant> for Instant {
407 type Output = Duration;
409 fn sub(self, other: Instant) -> Duration {
410 self.duration_since(other)
414 #[stable(feature = "time2", since = "1.8.0")]
415 impl fmt::Debug for Instant {
416 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
422 /// An anchor in time which can be used to create new `SystemTime` instances or
423 /// learn about where in time a `SystemTime` lies.
425 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
426 /// respect to the system clock. Using `duration_since` on an existing
427 /// `SystemTime` instance can tell how far away from this point in time a
428 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
429 /// `SystemTime` instance to represent another fixed point in time.
434 /// use std::time::SystemTime;
436 /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
437 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
438 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
441 #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
442 pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
444 /// Returns the system time corresponding to "now".
449 /// use std::time::SystemTime;
451 /// let sys_time = SystemTime::now();
453 #[stable(feature = "time2", since = "1.8.0")]
454 pub fn now() -> SystemTime {
455 SystemTime(time::SystemTime::now())
458 /// Returns the amount of time elapsed from an earlier point in time.
460 /// This function may fail because measurements taken earlier are not
461 /// guaranteed to always be before later measurements (due to anomalies such
462 /// as the system clock being adjusted either forwards or backwards).
463 /// [`Instant`] can be used to measure elapsed time without this risk of failure.
465 /// If successful, [`Ok`]`(`[`Duration`]`)` is returned where the duration represents
466 /// the amount of time elapsed from the specified measurement to this one.
468 /// Returns an [`Err`] if `earlier` is later than `self`, and the error
469 /// contains how far from `self` the time is.
474 /// use std::time::SystemTime;
476 /// let sys_time = SystemTime::now();
477 /// let new_sys_time = SystemTime::now();
478 /// let difference = new_sys_time.duration_since(sys_time)
479 /// .expect("Clock may have gone backwards");
480 /// println!("{:?}", difference);
482 #[stable(feature = "time2", since = "1.8.0")]
483 pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
484 self.0.sub_time(&earlier.0).map_err(SystemTimeError)
487 /// Returns the difference between the clock time when this
488 /// system time was created, and the current clock time.
490 /// This function may fail as the underlying system clock is susceptible to
491 /// drift and updates (e.g., the system clock could go backwards), so this
492 /// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is
493 /// returned where the duration represents the amount of time elapsed from
494 /// this time measurement to the current time.
496 /// To measure elapsed time reliably, use [`Instant`] instead.
498 /// Returns an [`Err`] if `self` is later than the current system time, and
499 /// the error contains how far from the current system time `self` is.
504 /// use std::thread::sleep;
505 /// use std::time::{Duration, SystemTime};
507 /// let sys_time = SystemTime::now();
508 /// let one_sec = Duration::from_secs(1);
510 /// assert!(sys_time.elapsed().unwrap() >= one_sec);
512 #[stable(feature = "time2", since = "1.8.0")]
513 pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
514 SystemTime::now().duration_since(*self)
517 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
518 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
520 #[stable(feature = "time_checked_add", since = "1.34.0")]
521 pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
522 self.0.checked_add_duration(&duration).map(SystemTime)
525 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
526 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
528 #[stable(feature = "time_checked_add", since = "1.34.0")]
529 pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
530 self.0.checked_sub_duration(&duration).map(SystemTime)
534 #[stable(feature = "time2", since = "1.8.0")]
535 impl Add<Duration> for SystemTime {
536 type Output = SystemTime;
540 /// This function may panic if the resulting point in time cannot be represented by the
541 /// underlying data structure. See [`SystemTime::checked_add`] for a version without panic.
542 fn add(self, dur: Duration) -> SystemTime {
543 self.checked_add(dur).expect("overflow when adding duration to instant")
547 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
548 impl AddAssign<Duration> for SystemTime {
549 fn add_assign(&mut self, other: Duration) {
550 *self = *self + other;
554 #[stable(feature = "time2", since = "1.8.0")]
555 impl Sub<Duration> for SystemTime {
556 type Output = SystemTime;
558 fn sub(self, dur: Duration) -> SystemTime {
559 self.checked_sub(dur).expect("overflow when subtracting duration from instant")
563 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
564 impl SubAssign<Duration> for SystemTime {
565 fn sub_assign(&mut self, other: Duration) {
566 *self = *self - other;
570 #[stable(feature = "time2", since = "1.8.0")]
571 impl fmt::Debug for SystemTime {
572 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
577 /// An anchor in time which can be used to create new `SystemTime` instances or
578 /// learn about where in time a `SystemTime` lies.
580 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
581 /// respect to the system clock. Using `duration_since` on an existing
582 /// [`SystemTime`] instance can tell how far away from this point in time a
583 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
584 /// [`SystemTime`] instance to represent another fixed point in time.
589 /// use std::time::{SystemTime, UNIX_EPOCH};
591 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
592 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
593 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
596 #[stable(feature = "time2", since = "1.8.0")]
597 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
599 impl SystemTimeError {
600 /// Returns the positive duration which represents how far forward the
601 /// second system time was from the first.
603 /// A `SystemTimeError` is returned from the [`SystemTime::duration_since`]
604 /// and [`SystemTime::elapsed`] methods whenever the second system time
605 /// represents a point later in time than the `self` of the method call.
610 /// use std::thread::sleep;
611 /// use std::time::{Duration, SystemTime};
613 /// let sys_time = SystemTime::now();
614 /// sleep(Duration::from_secs(1));
615 /// let new_sys_time = SystemTime::now();
616 /// match sys_time.duration_since(new_sys_time) {
618 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
621 #[stable(feature = "time2", since = "1.8.0")]
622 pub fn duration(&self) -> Duration {
627 #[stable(feature = "time2", since = "1.8.0")]
628 impl Error for SystemTimeError {
630 fn description(&self) -> &str {
631 "other time was not earlier than self"
635 #[stable(feature = "time2", since = "1.8.0")]
636 impl fmt::Display for SystemTimeError {
637 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
638 write!(f, "second time provided was later than self")
642 impl FromInner<time::SystemTime> for SystemTime {
643 fn from_inner(time: time::SystemTime) -> SystemTime {