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::Mutex;
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.
103 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
104 #[stable(feature = "time2", since = "1.8.0")]
105 pub struct Instant(time::Instant);
107 /// A measurement of the system clock, useful for talking to
108 /// external entities like the file system or other processes.
110 /// Distinct from the [`Instant`] type, this time measurement **is not
111 /// monotonic**. This means that you can save a file to the file system, then
112 /// save another file to the file system, **and the second file has a
113 /// `SystemTime` measurement earlier than the first**. In other words, an
114 /// operation that happens after another operation in real time may have an
115 /// earlier `SystemTime`!
117 /// Consequently, comparing two `SystemTime` instances to learn about the
118 /// duration between them returns a [`Result`] instead of an infallible [`Duration`]
119 /// to indicate that this sort of time drift may happen and needs to be handled.
121 /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
122 /// constant is provided in this module as an anchor in time to learn
123 /// information about a `SystemTime`. By calculating the duration from this
124 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
125 /// or perhaps some other string representation.
127 /// The size of a `SystemTime` struct may vary depending on the target operating
133 /// use std::time::{Duration, SystemTime};
134 /// use std::thread::sleep;
137 /// let now = SystemTime::now();
139 /// // we sleep for 2 seconds
140 /// sleep(Duration::new(2, 0));
141 /// match now.elapsed() {
144 /// println!("{}", elapsed.as_secs());
147 /// // an error occurred!
148 /// println!("Error: {:?}", e);
154 /// # Underlying System calls
155 /// Currently, the following system calls are being used to get the current time using `now()`:
157 /// | Platform | System call |
158 /// |:---------:|:--------------------------------------------------------------------:|
159 /// | CloudABI | [clock_time_get (Realtime Clock)] |
160 /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
161 /// | UNIX | [clock_gettime (Realtime Clock)] |
162 /// | DARWIN | [gettimeofday] |
163 /// | VXWorks | [clock_gettime (Realtime Clock)] |
164 /// | WASI | [__wasi_clock_time_get (Realtime Clock)] |
165 /// | Windows | [GetSystemTimePreciseAsFileTime] / [GetSystemTimeAsFileTime] |
167 /// [clock_time_get (Realtime Clock)]: https://nuxi.nl/cloudabi/#clock_time_get
168 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
169 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
170 /// [gettimeofday]: http://man7.org/linux/man-pages/man2/gettimeofday.2.html
171 /// [clock_gettime (Realtime Clock)]: https://linux.die.net/man/3/clock_gettime
172 /// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
173 /// [GetSystemTimePreciseAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
174 /// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime
176 /// **Disclaimer:** These system calls might change over time.
177 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
178 #[stable(feature = "time2", since = "1.8.0")]
179 pub struct SystemTime(time::SystemTime);
181 /// An error returned from the `duration_since` and `elapsed` methods on
182 /// `SystemTime`, used to learn how far in the opposite direction a system time
188 /// use std::thread::sleep;
189 /// use std::time::{Duration, SystemTime};
191 /// let sys_time = SystemTime::now();
192 /// sleep(Duration::from_secs(1));
193 /// let new_sys_time = SystemTime::now();
194 /// match sys_time.duration_since(new_sys_time) {
196 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
199 #[derive(Clone, Debug)]
200 #[stable(feature = "time2", since = "1.8.0")]
201 pub struct SystemTimeError(Duration);
204 /// Returns an instant corresponding to "now".
209 /// use std::time::Instant;
211 /// let now = Instant::now();
213 #[stable(feature = "time2", since = "1.8.0")]
214 pub fn now() -> Instant {
215 let os_now = time::Instant::now();
217 // And here we come upon a sad state of affairs. The whole point of
218 // `Instant` is that it's monotonically increasing. We've found in the
219 // wild, however, that it's not actually monotonically increasing for
220 // one reason or another. These appear to be OS and hardware level bugs,
221 // and there's not really a whole lot we can do about them. Here's a
222 // taste of what we've found:
224 // * #48514 - OpenBSD, x86_64
225 // * #49281 - linux arm64 and s390x
226 // * #51648 - windows, x86
227 // * #56560 - windows, x86_64, AWS
228 // * #56612 - windows, x86, vm (?)
229 // * #56940 - linux, arm64
230 // * https://bugzilla.mozilla.org/show_bug.cgi?id=1487778 - a similar
233 // It seems that this just happens a lot in the wild.
234 // We're seeing panics across various platforms where consecutive calls
235 // to `Instant::now`, such as via the `elapsed` function, are panicking
236 // as they're going backwards. Placed here is a last-ditch effort to try
237 // to fix things up. We keep a global "latest now" instance which is
238 // returned instead of what the OS says if the OS goes backwards.
240 // To hopefully mitigate the impact of this, a few platforms are
241 // excluded as "these at least haven't gone backwards yet".
242 if time::Instant::actually_monotonic() {
243 return Instant(os_now);
246 static LOCK: Mutex = Mutex::new();
247 static mut LAST_NOW: time::Instant = time::Instant::zero();
249 let _lock = LOCK.lock();
250 let now = cmp::max(LAST_NOW, os_now);
256 /// Returns the amount of time elapsed from another instant to this one.
260 /// This function will panic if `earlier` is later than `self`.
265 /// use std::time::{Duration, Instant};
266 /// use std::thread::sleep;
268 /// let now = Instant::now();
269 /// sleep(Duration::new(1, 0));
270 /// let new_now = Instant::now();
271 /// println!("{:?}", new_now.duration_since(now));
273 #[stable(feature = "time2", since = "1.8.0")]
274 pub fn duration_since(&self, earlier: Instant) -> Duration {
275 self.0.checked_sub_instant(&earlier.0).expect("supplied instant is later than self")
278 /// Returns the amount of time elapsed from another instant to this one,
279 /// or None if that instant is later than this one.
284 /// use std::time::{Duration, Instant};
285 /// use std::thread::sleep;
287 /// let now = Instant::now();
288 /// sleep(Duration::new(1, 0));
289 /// let new_now = Instant::now();
290 /// println!("{:?}", new_now.checked_duration_since(now));
291 /// println!("{:?}", now.checked_duration_since(new_now)); // None
293 #[stable(feature = "checked_duration_since", since = "1.39.0")]
294 pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
295 self.0.checked_sub_instant(&earlier.0)
298 /// Returns the amount of time elapsed from another instant to this one,
299 /// or zero duration if that instant is later than this one.
304 /// use std::time::{Duration, Instant};
305 /// use std::thread::sleep;
307 /// let now = Instant::now();
308 /// sleep(Duration::new(1, 0));
309 /// let new_now = Instant::now();
310 /// println!("{:?}", new_now.saturating_duration_since(now));
311 /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
313 #[stable(feature = "checked_duration_since", since = "1.39.0")]
314 pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
315 self.checked_duration_since(earlier).unwrap_or(Duration::new(0, 0))
318 /// Returns the amount of time elapsed since this instant was created.
322 /// This function may panic if the current time is earlier than this
323 /// instant, which is something that can happen if an `Instant` is
324 /// produced synthetically.
329 /// use std::thread::sleep;
330 /// use std::time::{Duration, Instant};
332 /// let instant = Instant::now();
333 /// let three_secs = Duration::from_secs(3);
334 /// sleep(three_secs);
335 /// assert!(instant.elapsed() >= three_secs);
337 #[stable(feature = "time2", since = "1.8.0")]
338 pub fn elapsed(&self) -> Duration {
339 Instant::now() - *self
342 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
343 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
345 #[stable(feature = "time_checked_add", since = "1.34.0")]
346 pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
347 self.0.checked_add_duration(&duration).map(Instant)
350 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
351 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
353 #[stable(feature = "time_checked_add", since = "1.34.0")]
354 pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
355 self.0.checked_sub_duration(&duration).map(Instant)
359 #[stable(feature = "time2", since = "1.8.0")]
360 impl Add<Duration> for Instant {
361 type Output = Instant;
365 /// This function may panic if the resulting point in time cannot be represented by the
366 /// underlying data structure. See [`Instant::checked_add`] for a version without panic.
367 fn add(self, other: Duration) -> Instant {
368 self.checked_add(other).expect("overflow when adding duration to instant")
372 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
373 impl AddAssign<Duration> for Instant {
374 fn add_assign(&mut self, other: Duration) {
375 *self = *self + other;
379 #[stable(feature = "time2", since = "1.8.0")]
380 impl Sub<Duration> for Instant {
381 type Output = Instant;
383 fn sub(self, other: Duration) -> Instant {
384 self.checked_sub(other).expect("overflow when subtracting duration from instant")
388 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
389 impl SubAssign<Duration> for Instant {
390 fn sub_assign(&mut self, other: Duration) {
391 *self = *self - other;
395 #[stable(feature = "time2", since = "1.8.0")]
396 impl Sub<Instant> for Instant {
397 type Output = Duration;
399 fn sub(self, other: Instant) -> Duration {
400 self.duration_since(other)
404 #[stable(feature = "time2", since = "1.8.0")]
405 impl fmt::Debug for Instant {
406 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
412 /// An anchor in time which can be used to create new `SystemTime` instances or
413 /// learn about where in time a `SystemTime` lies.
415 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
416 /// respect to the system clock. Using `duration_since` on an existing
417 /// `SystemTime` instance can tell how far away from this point in time a
418 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
419 /// `SystemTime` instance to represent another fixed point in time.
424 /// use std::time::SystemTime;
426 /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
427 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
428 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
431 #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
432 pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
434 /// Returns the system time corresponding to "now".
439 /// use std::time::SystemTime;
441 /// let sys_time = SystemTime::now();
443 #[stable(feature = "time2", since = "1.8.0")]
444 pub fn now() -> SystemTime {
445 SystemTime(time::SystemTime::now())
448 /// Returns the amount of time elapsed from an earlier point in time.
450 /// This function may fail because measurements taken earlier are not
451 /// guaranteed to always be before later measurements (due to anomalies such
452 /// as the system clock being adjusted either forwards or backwards).
453 /// [`Instant`] can be used to measure elapsed time without this risk of failure.
455 /// If successful, [`Ok`]`(`[`Duration`]`)` is returned where the duration represents
456 /// the amount of time elapsed from the specified measurement to this one.
458 /// Returns an [`Err`] if `earlier` is later than `self`, and the error
459 /// contains how far from `self` the time is.
464 /// use std::time::SystemTime;
466 /// let sys_time = SystemTime::now();
467 /// let difference = sys_time.duration_since(sys_time)
468 /// .expect("Clock may have gone backwards");
469 /// println!("{:?}", difference);
471 #[stable(feature = "time2", since = "1.8.0")]
472 pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
473 self.0.sub_time(&earlier.0).map_err(SystemTimeError)
476 /// Returns the difference between the clock time when this
477 /// system time was created, and the current clock time.
479 /// This function may fail as the underlying system clock is susceptible to
480 /// drift and updates (e.g., the system clock could go backwards), so this
481 /// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is
482 /// returned where the duration represents the amount of time elapsed from
483 /// this time measurement to the current time.
485 /// To measure elapsed time reliably, use [`Instant`] instead.
487 /// Returns an [`Err`] if `self` is later than the current system time, and
488 /// the error contains how far from the current system time `self` is.
493 /// use std::thread::sleep;
494 /// use std::time::{Duration, SystemTime};
496 /// let sys_time = SystemTime::now();
497 /// let one_sec = Duration::from_secs(1);
499 /// assert!(sys_time.elapsed().unwrap() >= one_sec);
501 #[stable(feature = "time2", since = "1.8.0")]
502 pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
503 SystemTime::now().duration_since(*self)
506 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
507 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
509 #[stable(feature = "time_checked_add", since = "1.34.0")]
510 pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
511 self.0.checked_add_duration(&duration).map(SystemTime)
514 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
515 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
517 #[stable(feature = "time_checked_add", since = "1.34.0")]
518 pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
519 self.0.checked_sub_duration(&duration).map(SystemTime)
523 #[stable(feature = "time2", since = "1.8.0")]
524 impl Add<Duration> for SystemTime {
525 type Output = SystemTime;
529 /// This function may panic if the resulting point in time cannot be represented by the
530 /// underlying data structure. See [`SystemTime::checked_add`] for a version without panic.
531 fn add(self, dur: Duration) -> SystemTime {
532 self.checked_add(dur).expect("overflow when adding duration to instant")
536 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
537 impl AddAssign<Duration> for SystemTime {
538 fn add_assign(&mut self, other: Duration) {
539 *self = *self + other;
543 #[stable(feature = "time2", since = "1.8.0")]
544 impl Sub<Duration> for SystemTime {
545 type Output = SystemTime;
547 fn sub(self, dur: Duration) -> SystemTime {
548 self.checked_sub(dur).expect("overflow when subtracting duration from instant")
552 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
553 impl SubAssign<Duration> for SystemTime {
554 fn sub_assign(&mut self, other: Duration) {
555 *self = *self - other;
559 #[stable(feature = "time2", since = "1.8.0")]
560 impl fmt::Debug for SystemTime {
561 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
566 /// An anchor in time which can be used to create new `SystemTime` instances or
567 /// learn about where in time a `SystemTime` lies.
569 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
570 /// respect to the system clock. Using `duration_since` on an existing
571 /// [`SystemTime`] instance can tell how far away from this point in time a
572 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
573 /// [`SystemTime`] instance to represent another fixed point in time.
578 /// use std::time::{SystemTime, UNIX_EPOCH};
580 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
581 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
582 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
585 #[stable(feature = "time2", since = "1.8.0")]
586 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
588 impl SystemTimeError {
589 /// Returns the positive duration which represents how far forward the
590 /// second system time was from the first.
592 /// A `SystemTimeError` is returned from the [`SystemTime::duration_since`]
593 /// and [`SystemTime::elapsed`] methods whenever the second system time
594 /// represents a point later in time than the `self` of the method call.
599 /// use std::thread::sleep;
600 /// use std::time::{Duration, SystemTime};
602 /// let sys_time = SystemTime::now();
603 /// sleep(Duration::from_secs(1));
604 /// let new_sys_time = SystemTime::now();
605 /// match sys_time.duration_since(new_sys_time) {
607 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
610 #[stable(feature = "time2", since = "1.8.0")]
611 pub fn duration(&self) -> Duration {
616 #[stable(feature = "time2", since = "1.8.0")]
617 impl Error for SystemTimeError {
619 fn description(&self) -> &str {
620 "other time was not earlier than self"
624 #[stable(feature = "time2", since = "1.8.0")]
625 impl fmt::Display for SystemTimeError {
626 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627 write!(f, "second time provided was later than self")
631 impl FromInner<time::SystemTime> for SystemTime {
632 fn from_inner(time: time::SystemTime) -> SystemTime {