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, IntoInner};
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_seconds = u64::MAX / 1_000_000_000;
99 /// let duration = Duration::new(max_seconds, 0);
100 /// println!("{:?}", now + duration);
103 /// # Underlying System calls
105 /// The following system calls are [currently] being used by `now()` to find out
106 /// the current time:
108 /// | Platform | System call |
109 /// |-----------|----------------------------------------------------------------------|
110 /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
111 /// | UNIX | [clock_gettime (Monotonic Clock)] |
112 /// | Darwin | [mach_absolute_time] |
113 /// | VXWorks | [clock_gettime (Monotonic Clock)] |
114 /// | SOLID | `get_tim` |
115 /// | WASI | [__wasi_clock_time_get (Monotonic Clock)] |
116 /// | Windows | [QueryPerformanceCounter] |
118 /// [currently]: crate::io#platform-specific-behavior
119 /// [QueryPerformanceCounter]: https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter
120 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
121 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
122 /// [__wasi_clock_time_get (Monotonic Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
123 /// [clock_gettime (Monotonic Clock)]: https://linux.die.net/man/3/clock_gettime
124 /// [mach_absolute_time]: https://developer.apple.com/library/archive/documentation/Darwin/Conceptual/KernelProgramming/services/services.html
126 /// **Disclaimer:** These system calls might change over time.
128 /// > Note: mathematical operations like [`add`] may panic if the underlying
129 /// > structure cannot represent the new point in time.
131 /// [`add`]: Instant::add
135 /// On all platforms `Instant` will try to use an OS API that guarantees monotonic behavior
136 /// if available, which is the case for all [tier 1] platforms.
137 /// In practice such guarantees are – under rare circumstances – broken by hardware, virtualization
138 /// or operating system bugs. To work around these bugs and platforms not offering monotonic clocks
139 /// [`duration_since`], [`elapsed`] and [`sub`] saturate to zero. In older Rust versions this
140 /// lead to a panic instead. [`checked_duration_since`] can be used to detect and handle situations
141 /// where monotonicity is violated, or `Instant`s are subtracted in the wrong order.
143 /// This workaround obscures programming errors where earlier and later instants are accidentally
144 /// swapped. For this reason future rust versions may reintroduce panics.
146 /// [tier 1]: https://doc.rust-lang.org/rustc/platform-support.html
147 /// [`duration_since`]: Instant::duration_since
148 /// [`elapsed`]: Instant::elapsed
149 /// [`sub`]: Instant::sub
150 /// [`checked_duration_since`]: Instant::checked_duration_since
152 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
153 #[stable(feature = "time2", since = "1.8.0")]
154 pub struct Instant(time::Instant);
156 /// A measurement of the system clock, useful for talking to
157 /// external entities like the file system or other processes.
159 /// Distinct from the [`Instant`] type, this time measurement **is not
160 /// monotonic**. This means that you can save a file to the file system, then
161 /// save another file to the file system, **and the second file has a
162 /// `SystemTime` measurement earlier than the first**. In other words, an
163 /// operation that happens after another operation in real time may have an
164 /// earlier `SystemTime`!
166 /// Consequently, comparing two `SystemTime` instances to learn about the
167 /// duration between them returns a [`Result`] instead of an infallible [`Duration`]
168 /// to indicate that this sort of time drift may happen and needs to be handled.
170 /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
171 /// constant is provided in this module as an anchor in time to learn
172 /// information about a `SystemTime`. By calculating the duration from this
173 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
174 /// or perhaps some other string representation.
176 /// The size of a `SystemTime` struct may vary depending on the target operating
182 /// use std::time::{Duration, SystemTime};
183 /// use std::thread::sleep;
186 /// let now = SystemTime::now();
188 /// // we sleep for 2 seconds
189 /// sleep(Duration::new(2, 0));
190 /// match now.elapsed() {
193 /// println!("{}", elapsed.as_secs());
196 /// // an error occurred!
197 /// println!("Error: {e:?}");
203 /// # Platform-specific behavior
205 /// The precision of `SystemTime` can depend on the underlying OS-specific time format.
206 /// For example, on Windows the time is represented in 100 nanosecond intervals whereas Linux
207 /// can represent nanosecond intervals.
209 /// The following system calls are [currently] being used by `now()` to find out
210 /// the current time:
212 /// | Platform | System call |
213 /// |-----------|----------------------------------------------------------------------|
214 /// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
215 /// | UNIX | [clock_gettime (Realtime Clock)] |
216 /// | Darwin | [gettimeofday] |
217 /// | VXWorks | [clock_gettime (Realtime Clock)] |
218 /// | SOLID | `SOLID_RTC_ReadTime` |
219 /// | WASI | [__wasi_clock_time_get (Realtime Clock)] |
220 /// | Windows | [GetSystemTimePreciseAsFileTime] / [GetSystemTimeAsFileTime] |
222 /// [currently]: crate::io#platform-specific-behavior
223 /// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
224 /// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
225 /// [gettimeofday]: https://man7.org/linux/man-pages/man2/gettimeofday.2.html
226 /// [clock_gettime (Realtime Clock)]: https://linux.die.net/man/3/clock_gettime
227 /// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#clock_time_get
228 /// [GetSystemTimePreciseAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
229 /// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime
231 /// **Disclaimer:** These system calls might change over time.
233 /// > Note: mathematical operations like [`add`] may panic if the underlying
234 /// > structure cannot represent the new point in time.
236 /// [`add`]: SystemTime::add
237 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
238 #[stable(feature = "time2", since = "1.8.0")]
239 pub struct SystemTime(time::SystemTime);
241 /// An error returned from the `duration_since` and `elapsed` methods on
242 /// `SystemTime`, used to learn how far in the opposite direction a system time
248 /// use std::thread::sleep;
249 /// use std::time::{Duration, SystemTime};
251 /// let sys_time = SystemTime::now();
252 /// sleep(Duration::from_secs(1));
253 /// let new_sys_time = SystemTime::now();
254 /// match sys_time.duration_since(new_sys_time) {
256 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
259 #[derive(Clone, Debug)]
260 #[stable(feature = "time2", since = "1.8.0")]
261 pub struct SystemTimeError(Duration);
264 /// Returns an instant corresponding to "now".
269 /// use std::time::Instant;
271 /// let now = Instant::now();
274 #[stable(feature = "time2", since = "1.8.0")]
275 pub fn now() -> Instant {
276 Instant(time::Instant::now())
279 /// Returns the amount of time elapsed from another instant to this one,
280 /// or zero duration if that instant is later than this one.
284 /// Previous rust versions panicked when `earlier` was later than `self`. Currently this
285 /// method saturates. Future versions may reintroduce the panic in some circumstances.
286 /// See [Monotonicity].
288 /// [Monotonicity]: Instant#monotonicity
293 /// use std::time::{Duration, Instant};
294 /// use std::thread::sleep;
296 /// let now = Instant::now();
297 /// sleep(Duration::new(1, 0));
298 /// let new_now = Instant::now();
299 /// println!("{:?}", new_now.duration_since(now));
300 /// println!("{:?}", now.duration_since(new_now)); // 0ns
303 #[stable(feature = "time2", since = "1.8.0")]
304 pub fn duration_since(&self, earlier: Instant) -> Duration {
305 self.checked_duration_since(earlier).unwrap_or_default()
308 /// Returns the amount of time elapsed from another instant to this one,
309 /// or None if that instant is later than this one.
311 /// Due to [monotonicity bugs], even under correct logical ordering of the passed `Instant`s,
312 /// this method can return `None`.
314 /// [monotonicity bugs]: Instant#monotonicity
319 /// use std::time::{Duration, Instant};
320 /// use std::thread::sleep;
322 /// let now = Instant::now();
323 /// sleep(Duration::new(1, 0));
324 /// let new_now = Instant::now();
325 /// println!("{:?}", new_now.checked_duration_since(now));
326 /// println!("{:?}", now.checked_duration_since(new_now)); // None
329 #[stable(feature = "checked_duration_since", since = "1.39.0")]
330 pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
331 self.0.checked_sub_instant(&earlier.0)
334 /// Returns the amount of time elapsed from another instant to this one,
335 /// or zero duration if that instant is later than this one.
340 /// use std::time::{Duration, Instant};
341 /// use std::thread::sleep;
343 /// let now = Instant::now();
344 /// sleep(Duration::new(1, 0));
345 /// let new_now = Instant::now();
346 /// println!("{:?}", new_now.saturating_duration_since(now));
347 /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
350 #[stable(feature = "checked_duration_since", since = "1.39.0")]
351 pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
352 self.checked_duration_since(earlier).unwrap_or_default()
355 /// Returns the amount of time elapsed since this instant was created.
359 /// Previous rust versions panicked when self was earlier than the current time. Currently this
360 /// method returns a Duration of zero in that case. Future versions may reintroduce the panic.
361 /// See [Monotonicity].
363 /// [Monotonicity]: Instant#monotonicity
368 /// use std::thread::sleep;
369 /// use std::time::{Duration, Instant};
371 /// let instant = Instant::now();
372 /// let three_secs = Duration::from_secs(3);
373 /// sleep(three_secs);
374 /// assert!(instant.elapsed() >= three_secs);
377 #[stable(feature = "time2", since = "1.8.0")]
378 pub fn elapsed(&self) -> Duration {
379 Instant::now() - *self
382 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
383 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
385 #[stable(feature = "time_checked_add", since = "1.34.0")]
386 pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
387 self.0.checked_add_duration(&duration).map(Instant)
390 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
391 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
393 #[stable(feature = "time_checked_add", since = "1.34.0")]
394 pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
395 self.0.checked_sub_duration(&duration).map(Instant)
399 #[stable(feature = "time2", since = "1.8.0")]
400 impl Add<Duration> for Instant {
401 type Output = Instant;
405 /// This function may panic if the resulting point in time cannot be represented by the
406 /// underlying data structure. See [`Instant::checked_add`] for a version without panic.
407 fn add(self, other: Duration) -> Instant {
408 self.checked_add(other).expect("overflow when adding duration to instant")
412 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
413 impl AddAssign<Duration> for Instant {
414 fn add_assign(&mut self, other: Duration) {
415 *self = *self + other;
419 #[stable(feature = "time2", since = "1.8.0")]
420 impl Sub<Duration> for Instant {
421 type Output = Instant;
423 fn sub(self, other: Duration) -> Instant {
424 self.checked_sub(other).expect("overflow when subtracting duration from instant")
428 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
429 impl SubAssign<Duration> for Instant {
430 fn sub_assign(&mut self, other: Duration) {
431 *self = *self - other;
435 #[stable(feature = "time2", since = "1.8.0")]
436 impl Sub<Instant> for Instant {
437 type Output = Duration;
439 /// Returns the amount of time elapsed from another instant to this one,
440 /// or zero duration if that instant is later than this one.
444 /// Previous rust versions panicked when `other` was later than `self`. Currently this
445 /// method saturates. Future versions may reintroduce the panic in some circumstances.
446 /// See [Monotonicity].
448 /// [Monotonicity]: Instant#monotonicity
449 fn sub(self, other: Instant) -> Duration {
450 self.duration_since(other)
454 #[stable(feature = "time2", since = "1.8.0")]
455 impl fmt::Debug for Instant {
456 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
462 /// An anchor in time which can be used to create new `SystemTime` instances or
463 /// learn about where in time a `SystemTime` lies.
465 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
466 /// respect to the system clock. Using `duration_since` on an existing
467 /// `SystemTime` instance can tell how far away from this point in time a
468 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
469 /// `SystemTime` instance to represent another fixed point in time.
474 /// use std::time::SystemTime;
476 /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
477 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
478 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
481 #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
482 pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
484 /// Returns the system time corresponding to "now".
489 /// use std::time::SystemTime;
491 /// let sys_time = SystemTime::now();
494 #[stable(feature = "time2", since = "1.8.0")]
495 pub fn now() -> SystemTime {
496 SystemTime(time::SystemTime::now())
499 /// Returns the amount of time elapsed from an earlier point in time.
501 /// This function may fail because measurements taken earlier are not
502 /// guaranteed to always be before later measurements (due to anomalies such
503 /// as the system clock being adjusted either forwards or backwards).
504 /// [`Instant`] can be used to measure elapsed time without this risk of failure.
506 /// If successful, <code>[Ok]\([Duration])</code> is returned where the duration represents
507 /// the amount of time elapsed from the specified measurement to this one.
509 /// Returns an [`Err`] if `earlier` is later than `self`, and the error
510 /// contains how far from `self` the time is.
515 /// use std::time::SystemTime;
517 /// let sys_time = SystemTime::now();
518 /// let new_sys_time = SystemTime::now();
519 /// let difference = new_sys_time.duration_since(sys_time)
520 /// .expect("Clock may have gone backwards");
521 /// println!("{difference:?}");
523 #[stable(feature = "time2", since = "1.8.0")]
524 pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
525 self.0.sub_time(&earlier.0).map_err(SystemTimeError)
528 /// Returns the difference between the clock time when this
529 /// system time was created, and the current clock time.
531 /// This function may fail as the underlying system clock is susceptible to
532 /// drift and updates (e.g., the system clock could go backwards), so this
533 /// function might not always succeed. If successful, <code>[Ok]\([Duration])</code> is
534 /// returned where the duration represents the amount of time elapsed from
535 /// this time measurement to the current time.
537 /// To measure elapsed time reliably, use [`Instant`] instead.
539 /// Returns an [`Err`] if `self` is later than the current system time, and
540 /// the error contains how far from the current system time `self` is.
545 /// use std::thread::sleep;
546 /// use std::time::{Duration, SystemTime};
548 /// let sys_time = SystemTime::now();
549 /// let one_sec = Duration::from_secs(1);
551 /// assert!(sys_time.elapsed().unwrap() >= one_sec);
553 #[stable(feature = "time2", since = "1.8.0")]
554 pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
555 SystemTime::now().duration_since(*self)
558 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
559 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
561 #[stable(feature = "time_checked_add", since = "1.34.0")]
562 pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
563 self.0.checked_add_duration(&duration).map(SystemTime)
566 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
567 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
569 #[stable(feature = "time_checked_add", since = "1.34.0")]
570 pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
571 self.0.checked_sub_duration(&duration).map(SystemTime)
575 #[stable(feature = "time2", since = "1.8.0")]
576 impl Add<Duration> for SystemTime {
577 type Output = SystemTime;
581 /// This function may panic if the resulting point in time cannot be represented by the
582 /// underlying data structure. See [`SystemTime::checked_add`] for a version without panic.
583 fn add(self, dur: Duration) -> SystemTime {
584 self.checked_add(dur).expect("overflow when adding duration to instant")
588 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
589 impl AddAssign<Duration> for SystemTime {
590 fn add_assign(&mut self, other: Duration) {
591 *self = *self + other;
595 #[stable(feature = "time2", since = "1.8.0")]
596 impl Sub<Duration> for SystemTime {
597 type Output = SystemTime;
599 fn sub(self, dur: Duration) -> SystemTime {
600 self.checked_sub(dur).expect("overflow when subtracting duration from instant")
604 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
605 impl SubAssign<Duration> for SystemTime {
606 fn sub_assign(&mut self, other: Duration) {
607 *self = *self - other;
611 #[stable(feature = "time2", since = "1.8.0")]
612 impl fmt::Debug for SystemTime {
613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
618 /// An anchor in time which can be used to create new `SystemTime` instances or
619 /// learn about where in time a `SystemTime` lies.
621 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
622 /// respect to the system clock. Using `duration_since` on an existing
623 /// [`SystemTime`] instance can tell how far away from this point in time a
624 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
625 /// [`SystemTime`] instance to represent another fixed point in time.
630 /// use std::time::{SystemTime, UNIX_EPOCH};
632 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
633 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
634 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
637 #[stable(feature = "time2", since = "1.8.0")]
638 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
640 impl SystemTimeError {
641 /// Returns the positive duration which represents how far forward the
642 /// second system time was from the first.
644 /// A `SystemTimeError` is returned from the [`SystemTime::duration_since`]
645 /// and [`SystemTime::elapsed`] methods whenever the second system time
646 /// represents a point later in time than the `self` of the method call.
651 /// use std::thread::sleep;
652 /// use std::time::{Duration, SystemTime};
654 /// let sys_time = SystemTime::now();
655 /// sleep(Duration::from_secs(1));
656 /// let new_sys_time = SystemTime::now();
657 /// match sys_time.duration_since(new_sys_time) {
659 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
663 #[stable(feature = "time2", since = "1.8.0")]
664 pub fn duration(&self) -> Duration {
669 #[stable(feature = "time2", since = "1.8.0")]
670 impl Error for SystemTimeError {
672 fn description(&self) -> &str {
673 "other time was not earlier than self"
677 #[stable(feature = "time2", since = "1.8.0")]
678 impl fmt::Display for SystemTimeError {
679 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
680 write!(f, "second time provided was later than self")
684 impl FromInner<time::SystemTime> for SystemTime {
685 fn from_inner(time: time::SystemTime) -> SystemTime {
690 impl IntoInner<time::SystemTime> for SystemTime {
691 fn into_inner(self) -> time::SystemTime {