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")]
37 use crate::error::Error;
39 use crate::ops::{Add, AddAssign, Sub, SubAssign};
41 use crate::sys_common::FromInner;
43 #[stable(feature = "time", since = "1.3.0")]
44 pub use core::time::Duration;
46 #[unstable(feature = "duration_checked_float", issue = "83400")]
47 pub use core::time::FromFloatSecsError;
49 /// A measurement of a monotonically nondecreasing clock.
50 /// Opaque and useful only with [`Duration`].
52 /// Instants are always guaranteed, barring [platform bugs], to be no less than any previously
53 /// measured instant when created, and are often useful for tasks such as measuring
54 /// benchmarks or timing how long an operation takes.
56 /// Note, however, that instants are **not** guaranteed to be **steady**. In other
57 /// words, each tick of the underlying clock might not be the same length (e.g.
58 /// some seconds may be longer than others). An instant may jump forwards or
59 /// experience time dilation (slow down or speed up), but it will never go
62 /// Instants are opaque types that can only be compared to one another. There is
63 /// no method to get "the number of seconds" from an instant. Instead, it only
64 /// allows measuring the duration between two instants (or comparing two
67 /// The size of an `Instant` struct may vary depending on the target operating
73 /// use std::time::{Duration, Instant};
74 /// use std::thread::sleep;
77 /// let now = Instant::now();
79 /// // we sleep for 2 seconds
80 /// sleep(Duration::new(2, 0));
82 /// println!("{}", now.elapsed().as_secs());
86 /// [platform bugs]: Instant#monotonicity
88 /// # OS-specific behaviors
90 /// An `Instant` is a wrapper around system-specific types and it may behave
91 /// differently depending on the underlying operating system. For example,
92 /// the following snippet is fine on Linux but panics on macOS:
95 /// use std::time::{Instant, Duration};
97 /// let now = Instant::now();
98 /// let max_nanoseconds = u64::MAX / 1_000_000_000;
99 /// let duration = Duration::new(max_nanoseconds, 0);
100 /// println!("{:?}", now + duration);
103 /// # Underlying System calls
104 /// Currently, the following system calls are being used to get the current time using `now()`:
106 /// | Platform | System call |
107 /// |-----------|----------------------------------------------------------------------|
108 /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
109 /// | UNIX | [clock_gettime (Monotonic Clock)] |
110 /// | Darwin | [mach_absolute_time] |
111 /// | VXWorks | [clock_gettime (Monotonic Clock)] |
112 /// | SOLID | `get_tim` |
113 /// | WASI | [__wasi_clock_time_get (Monotonic Clock)] |
114 /// | Windows | [QueryPerformanceCounter] |
116 /// [QueryPerformanceCounter]: https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter
117 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
118 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
119 /// [__wasi_clock_time_get (Monotonic Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
120 /// [clock_gettime (Monotonic Clock)]: https://linux.die.net/man/3/clock_gettime
121 /// [mach_absolute_time]: https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/KernelProgramming/services/services.html
123 /// **Disclaimer:** These system calls might change over time.
125 /// > Note: mathematical operations like [`add`] may panic if the underlying
126 /// > structure cannot represent the new point in time.
128 /// [`add`]: Instant::add
132 /// On all platforms `Instant` will try to use an OS API that guarantees monotonic behavior
133 /// if available, which is the case for all [tier 1] platforms.
134 /// In practice such guarantees are – under rare circumstances – broken by hardware, virtualization
135 /// or operating system bugs. To work around these bugs and platforms not offering monotonic clocks
136 /// [`duration_since`], [`elapsed`] and [`sub`] saturate to zero. In older Rust versions this
137 /// lead to a panic instead. [`checked_duration_since`] can be used to detect and handle situations
138 /// where monotonicity is violated, or `Instant`s are subtracted in the wrong order.
140 /// This workaround obscures programming errors where earlier and later instants are accidentally
141 /// swapped. For this reason future rust versions may reintroduce panics.
143 /// [tier 1]: https://doc.rust-lang.org/rustc/platform-support.html
144 /// [`duration_since`]: Instant::duration_since
145 /// [`elapsed`]: Instant::elapsed
146 /// [`sub`]: Instant::sub
147 /// [`checked_duration_since`]: Instant::checked_duration_since
149 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
150 #[stable(feature = "time2", since = "1.8.0")]
151 pub struct Instant(time::Instant);
153 /// A measurement of the system clock, useful for talking to
154 /// external entities like the file system or other processes.
156 /// Distinct from the [`Instant`] type, this time measurement **is not
157 /// monotonic**. This means that you can save a file to the file system, then
158 /// save another file to the file system, **and the second file has a
159 /// `SystemTime` measurement earlier than the first**. In other words, an
160 /// operation that happens after another operation in real time may have an
161 /// earlier `SystemTime`!
163 /// Consequently, comparing two `SystemTime` instances to learn about the
164 /// duration between them returns a [`Result`] instead of an infallible [`Duration`]
165 /// to indicate that this sort of time drift may happen and needs to be handled.
167 /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
168 /// constant is provided in this module as an anchor in time to learn
169 /// information about a `SystemTime`. By calculating the duration from this
170 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
171 /// or perhaps some other string representation.
173 /// The size of a `SystemTime` struct may vary depending on the target operating
179 /// use std::time::{Duration, SystemTime};
180 /// use std::thread::sleep;
183 /// let now = SystemTime::now();
185 /// // we sleep for 2 seconds
186 /// sleep(Duration::new(2, 0));
187 /// match now.elapsed() {
190 /// println!("{}", elapsed.as_secs());
193 /// // an error occurred!
194 /// println!("Error: {e:?}");
200 /// # Platform-specific behavior
202 /// The precision of `SystemTime` can depend on the underlying OS-specific time format.
203 /// For example, on Windows the time is represented in 100 nanosecond intervals whereas Linux
204 /// can represent nanosecond intervals.
206 /// Currently, the following system calls are being used to get the current time using `now()`:
208 /// | Platform | System call |
209 /// |-----------|----------------------------------------------------------------------|
210 /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
211 /// | UNIX | [clock_gettime (Realtime Clock)] |
212 /// | Darwin | [gettimeofday] |
213 /// | VXWorks | [clock_gettime (Realtime Clock)] |
214 /// | SOLID | `SOLID_RTC_ReadTime` |
215 /// | WASI | [__wasi_clock_time_get (Realtime Clock)] |
216 /// | Windows | [GetSystemTimePreciseAsFileTime] / [GetSystemTimeAsFileTime] |
218 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
219 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
220 /// [gettimeofday]: https://man7.org/linux/man-pages/man2/gettimeofday.2.html
221 /// [clock_gettime (Realtime Clock)]: https://linux.die.net/man/3/clock_gettime
222 /// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
223 /// [GetSystemTimePreciseAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
224 /// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime
226 /// **Disclaimer:** These system calls might change over time.
228 /// > Note: mathematical operations like [`add`] may panic if the underlying
229 /// > structure cannot represent the new point in time.
231 /// [`add`]: SystemTime::add
232 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
233 #[stable(feature = "time2", since = "1.8.0")]
234 pub struct SystemTime(time::SystemTime);
236 /// An error returned from the `duration_since` and `elapsed` methods on
237 /// `SystemTime`, used to learn how far in the opposite direction a system time
243 /// use std::thread::sleep;
244 /// use std::time::{Duration, SystemTime};
246 /// let sys_time = SystemTime::now();
247 /// sleep(Duration::from_secs(1));
248 /// let new_sys_time = SystemTime::now();
249 /// match sys_time.duration_since(new_sys_time) {
251 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
254 #[derive(Clone, Debug)]
255 #[stable(feature = "time2", since = "1.8.0")]
256 pub struct SystemTimeError(Duration);
259 /// Returns an instant corresponding to "now".
264 /// use std::time::Instant;
266 /// let now = Instant::now();
269 #[stable(feature = "time2", since = "1.8.0")]
270 pub fn now() -> Instant {
271 Instant(time::Instant::now())
274 /// Returns the amount of time elapsed from another instant to this one,
275 /// or zero duration if that instant is later than this one.
279 /// Previous rust versions panicked when `earlier` was later than `self`. Currently this
280 /// method saturates. Future versions may reintroduce the panic in some circumstances.
281 /// See [Monotonicity].
283 /// [Monotonicity]: Instant#monotonicity
288 /// use std::time::{Duration, Instant};
289 /// use std::thread::sleep;
291 /// let now = Instant::now();
292 /// sleep(Duration::new(1, 0));
293 /// let new_now = Instant::now();
294 /// println!("{:?}", new_now.duration_since(now));
295 /// println!("{:?}", now.duration_since(new_now)); // 0ns
298 #[stable(feature = "time2", since = "1.8.0")]
299 pub fn duration_since(&self, earlier: Instant) -> Duration {
300 self.checked_duration_since(earlier).unwrap_or_default()
303 /// Returns the amount of time elapsed from another instant to this one,
304 /// or None if that instant is later than this one.
306 /// Due to [monotonicity bugs], even under correct logical ordering of the passed `Instant`s,
307 /// this method can return `None`.
309 /// [monotonicity bugs]: Instant#monotonicity
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.checked_duration_since(now));
321 /// println!("{:?}", now.checked_duration_since(new_now)); // None
324 #[stable(feature = "checked_duration_since", since = "1.39.0")]
325 pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
326 self.0.checked_sub_instant(&earlier.0)
329 /// Returns the amount of time elapsed from another instant to this one,
330 /// or zero duration if that instant is later than this one.
335 /// use std::time::{Duration, Instant};
336 /// use std::thread::sleep;
338 /// let now = Instant::now();
339 /// sleep(Duration::new(1, 0));
340 /// let new_now = Instant::now();
341 /// println!("{:?}", new_now.saturating_duration_since(now));
342 /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
345 #[stable(feature = "checked_duration_since", since = "1.39.0")]
346 pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
347 self.checked_duration_since(earlier).unwrap_or_default()
350 /// Returns the amount of time elapsed since this instant was created.
354 /// Previous rust versions panicked when self was earlier than the current time. Currently this
355 /// method returns a Duration of zero in that case. Future versions may reintroduce the panic.
356 /// See [Monotonicity].
358 /// [Monotonicity]: Instant#monotonicity
363 /// use std::thread::sleep;
364 /// use std::time::{Duration, Instant};
366 /// let instant = Instant::now();
367 /// let three_secs = Duration::from_secs(3);
368 /// sleep(three_secs);
369 /// assert!(instant.elapsed() >= three_secs);
372 #[stable(feature = "time2", since = "1.8.0")]
373 pub fn elapsed(&self) -> Duration {
374 Instant::now() - *self
377 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
378 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
380 #[stable(feature = "time_checked_add", since = "1.34.0")]
381 pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
382 self.0.checked_add_duration(&duration).map(Instant)
385 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
386 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
388 #[stable(feature = "time_checked_add", since = "1.34.0")]
389 pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
390 self.0.checked_sub_duration(&duration).map(Instant)
394 #[stable(feature = "time2", since = "1.8.0")]
395 impl Add<Duration> for Instant {
396 type Output = Instant;
400 /// This function may panic if the resulting point in time cannot be represented by the
401 /// underlying data structure. See [`Instant::checked_add`] for a version without panic.
402 fn add(self, other: Duration) -> Instant {
403 self.checked_add(other).expect("overflow when adding duration to instant")
407 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
408 impl AddAssign<Duration> for Instant {
409 fn add_assign(&mut self, other: Duration) {
410 *self = *self + other;
414 #[stable(feature = "time2", since = "1.8.0")]
415 impl Sub<Duration> for Instant {
416 type Output = Instant;
418 fn sub(self, other: Duration) -> Instant {
419 self.checked_sub(other).expect("overflow when subtracting duration from instant")
423 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
424 impl SubAssign<Duration> for Instant {
425 fn sub_assign(&mut self, other: Duration) {
426 *self = *self - other;
430 #[stable(feature = "time2", since = "1.8.0")]
431 impl Sub<Instant> for Instant {
432 type Output = Duration;
434 /// Returns the amount of time elapsed from another instant to this one,
435 /// or zero duration if that instant is later than this one.
439 /// Previous rust versions panicked when `other` was later than `self`. Currently this
440 /// method saturates. Future versions may reintroduce the panic in some circumstances.
441 /// See [Monotonicity].
443 /// [Monotonicity]: Instant#monotonicity
444 fn sub(self, other: Instant) -> Duration {
445 self.duration_since(other)
449 #[stable(feature = "time2", since = "1.8.0")]
450 impl fmt::Debug for Instant {
451 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457 /// An anchor in time which can be used to create new `SystemTime` instances or
458 /// learn about where in time a `SystemTime` lies.
460 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
461 /// respect to the system clock. Using `duration_since` on an existing
462 /// `SystemTime` instance can tell how far away from this point in time a
463 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
464 /// `SystemTime` instance to represent another fixed point in time.
469 /// use std::time::SystemTime;
471 /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
472 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
473 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
476 #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
477 pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
479 /// Returns the system time corresponding to "now".
484 /// use std::time::SystemTime;
486 /// let sys_time = SystemTime::now();
489 #[stable(feature = "time2", since = "1.8.0")]
490 pub fn now() -> SystemTime {
491 SystemTime(time::SystemTime::now())
494 /// Returns the amount of time elapsed from an earlier point in time.
496 /// This function may fail because measurements taken earlier are not
497 /// guaranteed to always be before later measurements (due to anomalies such
498 /// as the system clock being adjusted either forwards or backwards).
499 /// [`Instant`] can be used to measure elapsed time without this risk of failure.
501 /// If successful, <code>[Ok]\([Duration])</code> is returned where the duration represents
502 /// the amount of time elapsed from the specified measurement to this one.
504 /// Returns an [`Err`] if `earlier` is later than `self`, and the error
505 /// contains how far from `self` the time is.
510 /// use std::time::SystemTime;
512 /// let sys_time = SystemTime::now();
513 /// let new_sys_time = SystemTime::now();
514 /// let difference = new_sys_time.duration_since(sys_time)
515 /// .expect("Clock may have gone backwards");
516 /// println!("{difference:?}");
518 #[stable(feature = "time2", since = "1.8.0")]
519 pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
520 self.0.sub_time(&earlier.0).map_err(SystemTimeError)
523 /// Returns the difference between the clock time when this
524 /// system time was created, and the current clock time.
526 /// This function may fail as the underlying system clock is susceptible to
527 /// drift and updates (e.g., the system clock could go backwards), so this
528 /// function might not always succeed. If successful, <code>[Ok]\([Duration])</code> is
529 /// returned where the duration represents the amount of time elapsed from
530 /// this time measurement to the current time.
532 /// To measure elapsed time reliably, use [`Instant`] instead.
534 /// Returns an [`Err`] if `self` is later than the current system time, and
535 /// the error contains how far from the current system time `self` is.
540 /// use std::thread::sleep;
541 /// use std::time::{Duration, SystemTime};
543 /// let sys_time = SystemTime::now();
544 /// let one_sec = Duration::from_secs(1);
546 /// assert!(sys_time.elapsed().unwrap() >= one_sec);
548 #[stable(feature = "time2", since = "1.8.0")]
549 pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
550 SystemTime::now().duration_since(*self)
553 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
554 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
556 #[stable(feature = "time_checked_add", since = "1.34.0")]
557 pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
558 self.0.checked_add_duration(&duration).map(SystemTime)
561 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
562 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
564 #[stable(feature = "time_checked_add", since = "1.34.0")]
565 pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
566 self.0.checked_sub_duration(&duration).map(SystemTime)
570 #[stable(feature = "time2", since = "1.8.0")]
571 impl Add<Duration> for SystemTime {
572 type Output = SystemTime;
576 /// This function may panic if the resulting point in time cannot be represented by the
577 /// underlying data structure. See [`SystemTime::checked_add`] for a version without panic.
578 fn add(self, dur: Duration) -> SystemTime {
579 self.checked_add(dur).expect("overflow when adding duration to instant")
583 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
584 impl AddAssign<Duration> for SystemTime {
585 fn add_assign(&mut self, other: Duration) {
586 *self = *self + other;
590 #[stable(feature = "time2", since = "1.8.0")]
591 impl Sub<Duration> for SystemTime {
592 type Output = SystemTime;
594 fn sub(self, dur: Duration) -> SystemTime {
595 self.checked_sub(dur).expect("overflow when subtracting duration from instant")
599 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
600 impl SubAssign<Duration> for SystemTime {
601 fn sub_assign(&mut self, other: Duration) {
602 *self = *self - other;
606 #[stable(feature = "time2", since = "1.8.0")]
607 impl fmt::Debug for SystemTime {
608 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
613 /// An anchor in time which can be used to create new `SystemTime` instances or
614 /// learn about where in time a `SystemTime` lies.
616 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
617 /// respect to the system clock. Using `duration_since` on an existing
618 /// [`SystemTime`] instance can tell how far away from this point in time a
619 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
620 /// [`SystemTime`] instance to represent another fixed point in time.
625 /// use std::time::{SystemTime, UNIX_EPOCH};
627 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
628 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
629 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
632 #[stable(feature = "time2", since = "1.8.0")]
633 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
635 impl SystemTimeError {
636 /// Returns the positive duration which represents how far forward the
637 /// second system time was from the first.
639 /// A `SystemTimeError` is returned from the [`SystemTime::duration_since`]
640 /// and [`SystemTime::elapsed`] methods whenever the second system time
641 /// represents a point later in time than the `self` of the method call.
646 /// use std::thread::sleep;
647 /// use std::time::{Duration, SystemTime};
649 /// let sys_time = SystemTime::now();
650 /// sleep(Duration::from_secs(1));
651 /// let new_sys_time = SystemTime::now();
652 /// match sys_time.duration_since(new_sys_time) {
654 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
658 #[stable(feature = "time2", since = "1.8.0")]
659 pub fn duration(&self) -> Duration {
664 #[stable(feature = "time2", since = "1.8.0")]
665 impl Error for SystemTimeError {
667 fn description(&self) -> &str {
668 "other time was not earlier than self"
672 #[stable(feature = "time2", since = "1.8.0")]
673 impl fmt::Display for SystemTimeError {
674 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
675 write!(f, "second time provided was later than self")
679 impl FromInner<time::SystemTime> for SystemTime {
680 fn from_inner(time: time::SystemTime) -> SystemTime {