1 //! Temporal quantification.
5 //! There are multiple ways to create a new [`Duration`]:
8 //! # use std::time::Duration;
9 //! let five_seconds = Duration::from_secs(5);
10 //! assert_eq!(five_seconds, Duration::from_millis(5_000));
11 //! assert_eq!(five_seconds, Duration::from_micros(5_000_000));
12 //! assert_eq!(five_seconds, Duration::from_nanos(5_000_000_000));
14 //! let ten_seconds = Duration::from_secs(10);
15 //! let seven_nanos = Duration::from_nanos(7);
16 //! let total = ten_seconds + seven_nanos;
17 //! assert_eq!(total, Duration::new(10, 7));
20 //! Using [`Instant`] to calculate how long a function took to run:
22 //! ```ignore (incomplete)
23 //! let now = Instant::now();
25 //! // Calling a slow function, it may take a while
28 //! let elapsed_time = now.elapsed();
29 //! println!("Running slow_function() took {} seconds.", elapsed_time.as_secs());
32 #![stable(feature = "time", since = "1.3.0")]
38 use crate::error::Error;
40 use crate::ops::{Add, AddAssign, Sub, SubAssign};
42 use crate::sys_common::FromInner;
44 #[stable(feature = "time", since = "1.3.0")]
45 pub use core::time::Duration;
47 #[unstable(feature = "duration_checked_float", issue = "83400")]
48 pub use core::time::FromFloatSecsError;
50 /// A measurement of a monotonically nondecreasing clock.
51 /// Opaque and useful only with [`Duration`].
53 /// Instants are always guaranteed to be no less than any previously measured
54 /// instant when created, and are often useful for tasks such as measuring
55 /// benchmarks or timing how long an operation takes.
57 /// Note, however, that instants are **not** guaranteed to be **steady**. In other
58 /// words, each tick of the underlying clock might not be the same length (e.g.
59 /// some seconds may be longer than others). An instant may jump forwards or
60 /// experience time dilation (slow down or speed up), but it will never go
63 /// Instants are opaque types that can only be compared to one another. There is
64 /// no method to get "the number of seconds" from an instant. Instead, it only
65 /// allows measuring the duration between two instants (or comparing two
68 /// The size of an `Instant` struct may vary depending on the target operating
74 /// use std::time::{Duration, Instant};
75 /// use std::thread::sleep;
78 /// let now = Instant::now();
80 /// // we sleep for 2 seconds
81 /// sleep(Duration::new(2, 0));
83 /// println!("{}", now.elapsed().as_secs());
87 /// # OS-specific behaviors
89 /// An `Instant` is a wrapper around system-specific types and it may behave
90 /// differently depending on the underlying operating system. For example,
91 /// the following snippet is fine on Linux but panics on macOS:
94 /// use std::time::{Instant, Duration};
96 /// let now = Instant::now();
97 /// let max_nanoseconds = u64::MAX / 1_000_000_000;
98 /// let duration = Duration::new(max_nanoseconds, 0);
99 /// println!("{:?}", now + duration);
102 /// # Underlying System calls
103 /// Currently, the following system calls are being used to get the current time using `now()`:
105 /// | Platform | System call |
106 /// |-----------|----------------------------------------------------------------------|
107 /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
108 /// | UNIX | [clock_gettime (Monotonic Clock)] |
109 /// | Darwin | [mach_absolute_time] |
110 /// | VXWorks | [clock_gettime (Monotonic Clock)] |
111 /// | SOLID | `get_tim` |
112 /// | WASI | [__wasi_clock_time_get (Monotonic Clock)] |
113 /// | Windows | [QueryPerformanceCounter] |
115 /// [QueryPerformanceCounter]: https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter
116 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
117 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
118 /// [__wasi_clock_time_get (Monotonic Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
119 /// [clock_gettime (Monotonic Clock)]: https://linux.die.net/man/3/clock_gettime
120 /// [mach_absolute_time]: https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/KernelProgramming/services/services.html
122 /// **Disclaimer:** These system calls might change over time.
124 /// > Note: mathematical operations like [`add`] may panic if the underlying
125 /// > structure cannot represent the new point in time.
127 /// [`add`]: Instant::add
128 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
129 #[stable(feature = "time2", since = "1.8.0")]
130 pub struct Instant(time::Instant);
132 /// A measurement of the system clock, useful for talking to
133 /// external entities like the file system or other processes.
135 /// Distinct from the [`Instant`] type, this time measurement **is not
136 /// monotonic**. This means that you can save a file to the file system, then
137 /// save another file to the file system, **and the second file has a
138 /// `SystemTime` measurement earlier than the first**. In other words, an
139 /// operation that happens after another operation in real time may have an
140 /// earlier `SystemTime`!
142 /// Consequently, comparing two `SystemTime` instances to learn about the
143 /// duration between them returns a [`Result`] instead of an infallible [`Duration`]
144 /// to indicate that this sort of time drift may happen and needs to be handled.
146 /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
147 /// constant is provided in this module as an anchor in time to learn
148 /// information about a `SystemTime`. By calculating the duration from this
149 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
150 /// or perhaps some other string representation.
152 /// The size of a `SystemTime` struct may vary depending on the target operating
158 /// use std::time::{Duration, SystemTime};
159 /// use std::thread::sleep;
162 /// let now = SystemTime::now();
164 /// // we sleep for 2 seconds
165 /// sleep(Duration::new(2, 0));
166 /// match now.elapsed() {
169 /// println!("{}", elapsed.as_secs());
172 /// // an error occurred!
173 /// println!("Error: {:?}", e);
179 /// # Platform-specific behavior
181 /// The precision of `SystemTime` can depend on the underlying OS-specific time format.
182 /// For example, on Windows the time is represented in 100 nanosecond intervals whereas Linux
183 /// can represent nanosecond intervals.
185 /// Currently, the following system calls are being used to get the current time using `now()`:
187 /// | Platform | System call |
188 /// |-----------|----------------------------------------------------------------------|
189 /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
190 /// | UNIX | [clock_gettime (Realtime Clock)] |
191 /// | Darwin | [gettimeofday] |
192 /// | VXWorks | [clock_gettime (Realtime Clock)] |
193 /// | SOLID | `SOLID_RTC_ReadTime` |
194 /// | WASI | [__wasi_clock_time_get (Realtime Clock)] |
195 /// | Windows | [GetSystemTimePreciseAsFileTime] / [GetSystemTimeAsFileTime] |
197 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
198 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
199 /// [gettimeofday]: https://man7.org/linux/man-pages/man2/gettimeofday.2.html
200 /// [clock_gettime (Realtime Clock)]: https://linux.die.net/man/3/clock_gettime
201 /// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
202 /// [GetSystemTimePreciseAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
203 /// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime
205 /// **Disclaimer:** These system calls might change over time.
207 /// > Note: mathematical operations like [`add`] may panic if the underlying
208 /// > structure cannot represent the new point in time.
210 /// [`add`]: SystemTime::add
211 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
212 #[stable(feature = "time2", since = "1.8.0")]
213 pub struct SystemTime(time::SystemTime);
215 /// An error returned from the `duration_since` and `elapsed` methods on
216 /// `SystemTime`, used to learn how far in the opposite direction a system time
222 /// use std::thread::sleep;
223 /// use std::time::{Duration, SystemTime};
225 /// let sys_time = SystemTime::now();
226 /// sleep(Duration::from_secs(1));
227 /// let new_sys_time = SystemTime::now();
228 /// match sys_time.duration_since(new_sys_time) {
230 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
233 #[derive(Clone, Debug)]
234 #[stable(feature = "time2", since = "1.8.0")]
235 pub struct SystemTimeError(Duration);
238 /// Returns an instant corresponding to "now".
243 /// use std::time::Instant;
245 /// let now = Instant::now();
248 #[stable(feature = "time2", since = "1.8.0")]
249 pub fn now() -> Instant {
250 let os_now = time::Instant::now();
252 // And here we come upon a sad state of affairs. The whole point of
253 // `Instant` is that it's monotonically increasing. We've found in the
254 // wild, however, that it's not actually monotonically increasing for
255 // one reason or another. These appear to be OS and hardware level bugs,
256 // and there's not really a whole lot we can do about them. Here's a
257 // taste of what we've found:
259 // * #48514 - OpenBSD, x86_64
260 // * #49281 - linux arm64 and s390x
261 // * #51648 - windows, x86
262 // * #56560 - windows, x86_64, AWS
263 // * #56612 - windows, x86, vm (?)
264 // * #56940 - linux, arm64
265 // * https://bugzilla.mozilla.org/show_bug.cgi?id=1487778 - a similar
268 // It seems that this just happens a lot in the wild.
269 // We're seeing panics across various platforms where consecutive calls
270 // to `Instant::now`, such as via the `elapsed` function, are panicking
271 // as they're going backwards. Placed here is a last-ditch effort to try
272 // to fix things up. We keep a global "latest now" instance which is
273 // returned instead of what the OS says if the OS goes backwards.
275 // To hopefully mitigate the impact of this, a few platforms are
276 // excluded as "these at least haven't gone backwards yet".
278 // While issues have been seen on arm64 platforms the Arm architecture
279 // requires that the counter monotonically increases and that it must
280 // provide a uniform view of system time (e.g. it must not be possible
281 // for a core to receive a message from another core with a time stamp
282 // and observe time going backwards (ARM DDI 0487G.b D11.1.2). While
283 // there have been a few 64bit SoCs that have bugs which cause time to
284 // not monoticially increase, these have been fixed in the Linux kernel
285 // and we shouldn't penalize all Arm SoCs for those who refuse to
286 // update their kernels:
287 // SUN50I_ERRATUM_UNKNOWN1 - Allwinner A64 / Pine A64 - fixed in 5.1
288 // FSL_ERRATUM_A008585 - Freescale LS2080A/LS1043A - fixed in 4.10
289 // HISILICON_ERRATUM_161010101 - Hisilicon 1610 - fixed in 4.11
290 // ARM64_ERRATUM_858921 - Cortex A73 - fixed in 4.12
291 if time::Instant::actually_monotonic() {
292 return Instant(os_now);
295 Instant(monotonic::monotonize(os_now))
298 /// Returns the amount of time elapsed from another instant to this one.
302 /// This function will panic if `earlier` is later than `self`.
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.duration_since(now));
316 #[stable(feature = "time2", since = "1.8.0")]
317 pub fn duration_since(&self, earlier: Instant) -> Duration {
318 self.0.checked_sub_instant(&earlier.0).expect("supplied instant is later than self")
321 /// Returns the amount of time elapsed from another instant to this one,
322 /// or None if that instant is later than this one.
327 /// use std::time::{Duration, Instant};
328 /// use std::thread::sleep;
330 /// let now = Instant::now();
331 /// sleep(Duration::new(1, 0));
332 /// let new_now = Instant::now();
333 /// println!("{:?}", new_now.checked_duration_since(now));
334 /// println!("{:?}", now.checked_duration_since(new_now)); // None
337 #[stable(feature = "checked_duration_since", since = "1.39.0")]
338 pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
339 self.0.checked_sub_instant(&earlier.0)
342 /// Returns the amount of time elapsed from another instant to this one,
343 /// or zero duration if that instant is later than this one.
348 /// use std::time::{Duration, Instant};
349 /// use std::thread::sleep;
351 /// let now = Instant::now();
352 /// sleep(Duration::new(1, 0));
353 /// let new_now = Instant::now();
354 /// println!("{:?}", new_now.saturating_duration_since(now));
355 /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
358 #[stable(feature = "checked_duration_since", since = "1.39.0")]
359 pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
360 self.checked_duration_since(earlier).unwrap_or_default()
363 /// Returns the amount of time elapsed since this instant was created.
367 /// This function may panic if the current time is earlier than this
368 /// instant, which is something that can happen if an `Instant` is
369 /// produced synthetically.
374 /// use std::thread::sleep;
375 /// use std::time::{Duration, Instant};
377 /// let instant = Instant::now();
378 /// let three_secs = Duration::from_secs(3);
379 /// sleep(three_secs);
380 /// assert!(instant.elapsed() >= three_secs);
383 #[stable(feature = "time2", since = "1.8.0")]
384 pub fn elapsed(&self) -> Duration {
385 Instant::now() - *self
388 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
389 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
391 #[stable(feature = "time_checked_add", since = "1.34.0")]
392 pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
393 self.0.checked_add_duration(&duration).map(Instant)
396 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
397 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
399 #[stable(feature = "time_checked_add", since = "1.34.0")]
400 pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
401 self.0.checked_sub_duration(&duration).map(Instant)
405 #[stable(feature = "time2", since = "1.8.0")]
406 impl Add<Duration> for Instant {
407 type Output = Instant;
411 /// This function may panic if the resulting point in time cannot be represented by the
412 /// underlying data structure. See [`Instant::checked_add`] for a version without panic.
413 fn add(self, other: Duration) -> Instant {
414 self.checked_add(other).expect("overflow when adding duration to instant")
418 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
419 impl AddAssign<Duration> for Instant {
420 fn add_assign(&mut self, other: Duration) {
421 *self = *self + other;
425 #[stable(feature = "time2", since = "1.8.0")]
426 impl Sub<Duration> for Instant {
427 type Output = Instant;
429 fn sub(self, other: Duration) -> Instant {
430 self.checked_sub(other).expect("overflow when subtracting duration from instant")
434 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
435 impl SubAssign<Duration> for Instant {
436 fn sub_assign(&mut self, other: Duration) {
437 *self = *self - other;
441 #[stable(feature = "time2", since = "1.8.0")]
442 impl Sub<Instant> for Instant {
443 type Output = Duration;
445 fn sub(self, other: Instant) -> Duration {
446 self.duration_since(other)
450 #[stable(feature = "time2", since = "1.8.0")]
451 impl fmt::Debug for Instant {
452 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
458 /// An anchor in time which can be used to create new `SystemTime` instances or
459 /// learn about where in time a `SystemTime` lies.
461 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
462 /// respect to the system clock. Using `duration_since` on an existing
463 /// `SystemTime` instance can tell how far away from this point in time a
464 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
465 /// `SystemTime` instance to represent another fixed point in time.
470 /// use std::time::SystemTime;
472 /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
473 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
474 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
477 #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
478 pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
480 /// Returns the system time corresponding to "now".
485 /// use std::time::SystemTime;
487 /// let sys_time = SystemTime::now();
490 #[stable(feature = "time2", since = "1.8.0")]
491 pub fn now() -> SystemTime {
492 SystemTime(time::SystemTime::now())
495 /// Returns the amount of time elapsed from an earlier point in time.
497 /// This function may fail because measurements taken earlier are not
498 /// guaranteed to always be before later measurements (due to anomalies such
499 /// as the system clock being adjusted either forwards or backwards).
500 /// [`Instant`] can be used to measure elapsed time without this risk of failure.
502 /// If successful, <code>[Ok]\([Duration])</code> is returned where the duration represents
503 /// the amount of time elapsed from the specified measurement to this one.
505 /// Returns an [`Err`] if `earlier` is later than `self`, and the error
506 /// contains how far from `self` the time is.
511 /// use std::time::SystemTime;
513 /// let sys_time = SystemTime::now();
514 /// let new_sys_time = SystemTime::now();
515 /// let difference = new_sys_time.duration_since(sys_time)
516 /// .expect("Clock may have gone backwards");
517 /// println!("{:?}", difference);
519 #[stable(feature = "time2", since = "1.8.0")]
520 pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
521 self.0.sub_time(&earlier.0).map_err(SystemTimeError)
524 /// Returns the difference between the clock time when this
525 /// system time was created, and the current clock time.
527 /// This function may fail as the underlying system clock is susceptible to
528 /// drift and updates (e.g., the system clock could go backwards), so this
529 /// function might not always succeed. If successful, <code>[Ok]\([Duration])</code> is
530 /// returned where the duration represents the amount of time elapsed from
531 /// this time measurement to the current time.
533 /// To measure elapsed time reliably, use [`Instant`] instead.
535 /// Returns an [`Err`] if `self` is later than the current system time, and
536 /// the error contains how far from the current system time `self` is.
541 /// use std::thread::sleep;
542 /// use std::time::{Duration, SystemTime};
544 /// let sys_time = SystemTime::now();
545 /// let one_sec = Duration::from_secs(1);
547 /// assert!(sys_time.elapsed().unwrap() >= one_sec);
549 #[stable(feature = "time2", since = "1.8.0")]
550 pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
551 SystemTime::now().duration_since(*self)
554 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
555 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
557 #[stable(feature = "time_checked_add", since = "1.34.0")]
558 pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
559 self.0.checked_add_duration(&duration).map(SystemTime)
562 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
563 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
565 #[stable(feature = "time_checked_add", since = "1.34.0")]
566 pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
567 self.0.checked_sub_duration(&duration).map(SystemTime)
571 #[stable(feature = "time2", since = "1.8.0")]
572 impl Add<Duration> for SystemTime {
573 type Output = SystemTime;
577 /// This function may panic if the resulting point in time cannot be represented by the
578 /// underlying data structure. See [`SystemTime::checked_add`] for a version without panic.
579 fn add(self, dur: Duration) -> SystemTime {
580 self.checked_add(dur).expect("overflow when adding duration to instant")
584 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
585 impl AddAssign<Duration> for SystemTime {
586 fn add_assign(&mut self, other: Duration) {
587 *self = *self + other;
591 #[stable(feature = "time2", since = "1.8.0")]
592 impl Sub<Duration> for SystemTime {
593 type Output = SystemTime;
595 fn sub(self, dur: Duration) -> SystemTime {
596 self.checked_sub(dur).expect("overflow when subtracting duration from instant")
600 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
601 impl SubAssign<Duration> for SystemTime {
602 fn sub_assign(&mut self, other: Duration) {
603 *self = *self - other;
607 #[stable(feature = "time2", since = "1.8.0")]
608 impl fmt::Debug for SystemTime {
609 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614 /// An anchor in time which can be used to create new `SystemTime` instances or
615 /// learn about where in time a `SystemTime` lies.
617 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
618 /// respect to the system clock. Using `duration_since` on an existing
619 /// [`SystemTime`] instance can tell how far away from this point in time a
620 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
621 /// [`SystemTime`] instance to represent another fixed point in time.
626 /// use std::time::{SystemTime, UNIX_EPOCH};
628 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
629 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
630 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
633 #[stable(feature = "time2", since = "1.8.0")]
634 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
636 impl SystemTimeError {
637 /// Returns the positive duration which represents how far forward the
638 /// second system time was from the first.
640 /// A `SystemTimeError` is returned from the [`SystemTime::duration_since`]
641 /// and [`SystemTime::elapsed`] methods whenever the second system time
642 /// represents a point later in time than the `self` of the method call.
647 /// use std::thread::sleep;
648 /// use std::time::{Duration, SystemTime};
650 /// let sys_time = SystemTime::now();
651 /// sleep(Duration::from_secs(1));
652 /// let new_sys_time = SystemTime::now();
653 /// match sys_time.duration_since(new_sys_time) {
655 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
659 #[stable(feature = "time2", since = "1.8.0")]
660 pub fn duration(&self) -> Duration {
665 #[stable(feature = "time2", since = "1.8.0")]
666 impl Error for SystemTimeError {
668 fn description(&self) -> &str {
669 "other time was not earlier than self"
673 #[stable(feature = "time2", since = "1.8.0")]
674 impl fmt::Display for SystemTimeError {
675 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
676 write!(f, "second time provided was later than self")
680 impl FromInner<time::SystemTime> for SystemTime {
681 fn from_inner(time: time::SystemTime) -> SystemTime {