std/time.rs
1//! Temporal quantification.
2//!
3//! # Examples
4//!
5//! There are multiple ways to create a new [`Duration`]:
6//!
7//! ```
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));
13//!
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));
18//! ```
19//!
20//! Using [`Instant`] to calculate how long a function took to run:
21//!
22//! ```ignore (incomplete)
23//! let now = Instant::now();
24//!
25//! // Calling a slow function, it may take a while
26//! slow_function();
27//!
28//! let elapsed_time = now.elapsed();
29//! println!("Running slow_function() took {} seconds.", elapsed_time.as_secs());
30//! ```
31
32#![stable(feature = "time", since = "1.3.0")]
33
34#[stable(feature = "time", since = "1.3.0")]
35pub use core::time::Duration;
36#[stable(feature = "duration_checked_float", since = "1.66.0")]
37pub use core::time::TryFromFloatSecsError;
38
39use crate::error::Error;
40use crate::fmt;
41use crate::ops::{Add, AddAssign, Sub, SubAssign};
42use crate::sys::{FromInner, IntoInner, time};
43
44/// A measurement of a monotonically nondecreasing clock.
45/// Opaque and useful only with [`Duration`].
46///
47/// Instants are always guaranteed, barring [platform bugs], to be no less than any previously
48/// measured instant when created, and are often useful for tasks such as measuring
49/// benchmarks or timing how long an operation takes.
50///
51/// Note, however, that instants are **not** guaranteed to be **steady**. In other
52/// words, each tick of the underlying clock might not be the same length (e.g.
53/// some seconds may be longer than others). An instant may jump forwards or
54/// experience time dilation (slow down or speed up), but it will never go
55/// backwards.
56/// As part of this non-guarantee it is also not specified whether system suspends count as
57/// elapsed time or not. The behavior varies across platforms and Rust versions.
58///
59/// Instants are opaque types that can only be compared to one another. There is
60/// no method to get "the number of seconds" from an instant. Instead, it only
61/// allows measuring the duration between two instants (or comparing two
62/// instants).
63///
64/// The size of an `Instant` struct may vary depending on the target operating
65/// system.
66///
67/// Example:
68///
69/// ```no_run
70/// use std::time::{Duration, Instant};
71/// use std::thread::sleep;
72///
73/// fn main() {
74/// let now = Instant::now();
75///
76/// // we sleep for 2 seconds
77/// sleep(Duration::new(2, 0));
78/// // it prints '2'
79/// println!("{}", now.elapsed().as_secs());
80/// }
81/// ```
82///
83/// [platform bugs]: Instant#monotonicity
84///
85/// # OS-specific behaviors
86///
87/// An `Instant` is a wrapper around system-specific types and it may behave
88/// differently depending on the underlying operating system. For example,
89/// the following snippet is fine on Linux but panics on macOS:
90///
91/// ```no_run
92/// use std::time::{Instant, Duration};
93///
94/// let now = Instant::now();
95/// let days_per_10_millennia = 365_2425;
96/// let solar_seconds_per_day = 60 * 60 * 24;
97/// let millennium_in_solar_seconds = 31_556_952_000;
98/// assert_eq!(millennium_in_solar_seconds, days_per_10_millennia * solar_seconds_per_day / 10);
99///
100/// let duration = Duration::new(millennium_in_solar_seconds, 0);
101/// println!("{:?}", now + duration);
102/// ```
103///
104/// For cross-platform code, you can comfortably use durations of up to around one hundred years.
105///
106/// # Underlying System calls
107///
108/// The following system calls are [currently] being used by `now()` to find out
109/// the current time:
110///
111/// | Platform | System call |
112/// |-----------|----------------------------------------------------------------------|
113/// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
114/// | UNIX | [clock_gettime] with `CLOCK_MONOTONIC` |
115/// | Darwin | [clock_gettime] with `CLOCK_UPTIME_RAW` |
116/// | VXWorks | [clock_gettime] with `CLOCK_MONOTONIC` |
117/// | SOLID | `get_tim` |
118/// | WASI | [__wasi_clock_time_get] with `monotonic` |
119/// | Windows | [QueryPerformanceCounter] |
120///
121/// [currently]: crate::io#platform-specific-behavior
122/// [QueryPerformanceCounter]: https://docs.microsoft.com/en-us/windows/win32/api/profileapi/nf-profileapi-queryperformancecounter
123/// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
124/// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
125/// [__wasi_clock_time_get]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#clock_time_get
126/// [clock_gettime]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/clock_getres.html
127///
128/// **Disclaimer:** These system calls might change over time.
129///
130/// > Note: mathematical operations like [`add`] may panic if the underlying
131/// > structure cannot represent the new point in time.
132///
133/// [`add`]: Instant::add
134///
135/// ## Monotonicity
136///
137/// On all platforms `Instant` will try to use an OS API that guarantees monotonic behavior
138/// if available, which is the case for all [tier 1] platforms.
139/// In practice such guarantees are – under rare circumstances – broken by hardware, virtualization
140/// or operating system bugs. To work around these bugs and platforms not offering monotonic clocks
141/// [`duration_since`], [`elapsed`] and [`sub`] saturate to zero. In older Rust versions this
142/// lead to a panic instead. [`checked_duration_since`] can be used to detect and handle situations
143/// where monotonicity is violated, or `Instant`s are subtracted in the wrong order.
144///
145/// This workaround obscures programming errors where earlier and later instants are accidentally
146/// swapped. For this reason future Rust versions may reintroduce panics.
147///
148/// [tier 1]: https://doc.rust-lang.org/rustc/platform-support.html
149/// [`duration_since`]: Instant::duration_since
150/// [`elapsed`]: Instant::elapsed
151/// [`sub`]: Instant::sub
152/// [`checked_duration_since`]: Instant::checked_duration_since
153///
154#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
155#[stable(feature = "time2", since = "1.8.0")]
156#[cfg_attr(not(test), rustc_diagnostic_item = "Instant")]
157pub struct Instant(time::Instant);
158
159/// A measurement of the system clock, useful for talking to
160/// external entities like the file system or other processes.
161///
162/// Distinct from the [`Instant`] type, this time measurement **is not
163/// monotonic**. This means that you can save a file to the file system, then
164/// save another file to the file system, **and the second file has a
165/// `SystemTime` measurement earlier than the first**. In other words, an
166/// operation that happens after another operation in real time may have an
167/// earlier `SystemTime`!
168///
169/// Consequently, comparing two `SystemTime` instances to learn about the
170/// duration between them returns a [`Result`] instead of an infallible [`Duration`]
171/// to indicate that this sort of time drift may happen and needs to be handled.
172///
173/// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
174/// constant is provided in this module as an anchor in time to learn
175/// information about a `SystemTime`. By calculating the duration from this
176/// fixed point in time, a `SystemTime` can be converted to a human-readable time,
177/// or perhaps some other string representation.
178///
179/// The size of a `SystemTime` struct may vary depending on the target operating
180/// system.
181///
182/// A `SystemTime` does not count leap seconds.
183/// `SystemTime::now()`'s behavior around a leap second
184/// is the same as the operating system's wall clock.
185/// The precise behavior near a leap second
186/// (e.g. whether the clock appears to run slow or fast, or stop, or jump)
187/// depends on platform and configuration,
188/// so should not be relied on.
189///
190/// Example:
191///
192/// ```no_run
193/// use std::time::{Duration, SystemTime};
194/// use std::thread::sleep;
195///
196/// fn main() {
197/// let now = SystemTime::now();
198///
199/// // we sleep for 2 seconds
200/// sleep(Duration::new(2, 0));
201/// match now.elapsed() {
202/// Ok(elapsed) => {
203/// // it prints '2'
204/// println!("{}", elapsed.as_secs());
205/// }
206/// Err(e) => {
207/// // the system clock went backwards!
208/// println!("Great Scott! {e:?}");
209/// }
210/// }
211/// }
212/// ```
213///
214/// # Platform-specific behavior
215///
216/// The precision of `SystemTime` can depend on the underlying OS-specific time format.
217/// For example, on Windows the time is represented in 100 nanosecond intervals whereas Linux
218/// can represent nanosecond intervals.
219///
220/// The following system calls are [currently] being used by `now()` to find out
221/// the current time:
222///
223/// | Platform | System call |
224/// |-----------|----------------------------------------------------------------------|
225/// | SGX | [`insecure_time` usercall]. More information on [timekeeping in SGX] |
226/// | UNIX | [clock_gettime (Realtime Clock)] |
227/// | Darwin | [clock_gettime (Realtime Clock)] |
228/// | VXWorks | [clock_gettime (Realtime Clock)] |
229/// | SOLID | `SOLID_RTC_ReadTime` |
230/// | WASI | [__wasi_clock_time_get (Realtime Clock)] |
231/// | Windows | [GetSystemTimePreciseAsFileTime] / [GetSystemTimeAsFileTime] |
232///
233/// [currently]: crate::io#platform-specific-behavior
234/// [`insecure_time` usercall]: https://edp.fortanix.com/docs/api/fortanix_sgx_abi/struct.Usercalls.html#method.insecure_time
235/// [timekeeping in SGX]: https://edp.fortanix.com/docs/concepts/rust-std/#codestdtimecode
236/// [clock_gettime (Realtime Clock)]: https://pubs.opengroup.org/onlinepubs/9799919799/functions/clock_getres.html
237/// [__wasi_clock_time_get (Realtime Clock)]: https://github.com/WebAssembly/WASI/blob/main/legacy/preview1/docs.md#clock_time_get
238/// [GetSystemTimePreciseAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
239/// [GetSystemTimeAsFileTime]: https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimeasfiletime
240///
241/// **Disclaimer:** These system calls might change over time.
242///
243/// > Note: mathematical operations like [`add`] may panic if the underlying
244/// > structure cannot represent the new point in time.
245///
246/// [`add`]: SystemTime::add
247/// [`UNIX_EPOCH`]: SystemTime::UNIX_EPOCH
248#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
249#[stable(feature = "time2", since = "1.8.0")]
250pub struct SystemTime(time::SystemTime);
251
252/// An error returned from the `duration_since` and `elapsed` methods on
253/// `SystemTime`, used to learn how far in the opposite direction a system time
254/// lies.
255///
256/// # Examples
257///
258/// ```no_run
259/// use std::thread::sleep;
260/// use std::time::{Duration, SystemTime};
261///
262/// let sys_time = SystemTime::now();
263/// sleep(Duration::from_secs(1));
264/// let new_sys_time = SystemTime::now();
265/// match sys_time.duration_since(new_sys_time) {
266/// Ok(_) => {}
267/// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
268/// }
269/// ```
270#[derive(Clone, Debug)]
271#[stable(feature = "time2", since = "1.8.0")]
272pub struct SystemTimeError(Duration);
273
274impl Instant {
275 /// Returns an instant corresponding to "now".
276 ///
277 /// # Examples
278 ///
279 /// ```
280 /// use std::time::Instant;
281 ///
282 /// let now = Instant::now();
283 /// ```
284 #[must_use]
285 #[stable(feature = "time2", since = "1.8.0")]
286 #[cfg_attr(not(test), rustc_diagnostic_item = "instant_now")]
287 pub fn now() -> Instant {
288 Instant(time::Instant::now())
289 }
290
291 /// Returns the amount of time elapsed from another instant to this one,
292 /// or zero duration if that instant is later than this one.
293 ///
294 /// # Panics
295 ///
296 /// Previous Rust versions panicked when `earlier` was later than `self`. Currently this
297 /// method saturates. Future versions may reintroduce the panic in some circumstances.
298 /// See [Monotonicity].
299 ///
300 /// [Monotonicity]: Instant#monotonicity
301 ///
302 /// # Examples
303 ///
304 /// ```no_run
305 /// use std::time::{Duration, Instant};
306 /// use std::thread::sleep;
307 ///
308 /// let now = Instant::now();
309 /// sleep(Duration::new(1, 0));
310 /// let new_now = Instant::now();
311 /// println!("{:?}", new_now.duration_since(now));
312 /// println!("{:?}", now.duration_since(new_now)); // 0ns
313 /// ```
314 #[must_use]
315 #[stable(feature = "time2", since = "1.8.0")]
316 pub fn duration_since(&self, earlier: Instant) -> Duration {
317 self.checked_duration_since(earlier).unwrap_or_default()
318 }
319
320 /// Returns the amount of time elapsed from another instant to this one,
321 /// or None if that instant is later than this one.
322 ///
323 /// Due to [monotonicity bugs], even under correct logical ordering of the passed `Instant`s,
324 /// this method can return `None`.
325 ///
326 /// [monotonicity bugs]: Instant#monotonicity
327 ///
328 /// # Examples
329 ///
330 /// ```no_run
331 /// use std::time::{Duration, Instant};
332 /// use std::thread::sleep;
333 ///
334 /// let now = Instant::now();
335 /// sleep(Duration::new(1, 0));
336 /// let new_now = Instant::now();
337 /// println!("{:?}", new_now.checked_duration_since(now));
338 /// println!("{:?}", now.checked_duration_since(new_now)); // None
339 /// ```
340 #[must_use]
341 #[stable(feature = "checked_duration_since", since = "1.39.0")]
342 pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration> {
343 self.0.checked_sub_instant(&earlier.0)
344 }
345
346 /// Returns the amount of time elapsed from another instant to this one,
347 /// or zero duration if that instant is later than this one.
348 ///
349 /// # Examples
350 ///
351 /// ```no_run
352 /// use std::time::{Duration, Instant};
353 /// use std::thread::sleep;
354 ///
355 /// let now = Instant::now();
356 /// sleep(Duration::new(1, 0));
357 /// let new_now = Instant::now();
358 /// println!("{:?}", new_now.saturating_duration_since(now));
359 /// println!("{:?}", now.saturating_duration_since(new_now)); // 0ns
360 /// ```
361 #[must_use]
362 #[stable(feature = "checked_duration_since", since = "1.39.0")]
363 pub fn saturating_duration_since(&self, earlier: Instant) -> Duration {
364 self.checked_duration_since(earlier).unwrap_or_default()
365 }
366
367 /// Returns the amount of time elapsed since this instant.
368 ///
369 /// # Panics
370 ///
371 /// Previous Rust versions panicked when the current time was earlier than self. Currently this
372 /// method returns a Duration of zero in that case. Future versions may reintroduce the panic.
373 /// See [Monotonicity].
374 ///
375 /// [Monotonicity]: Instant#monotonicity
376 ///
377 /// # Examples
378 ///
379 /// ```no_run
380 /// use std::thread::sleep;
381 /// use std::time::{Duration, Instant};
382 ///
383 /// let instant = Instant::now();
384 /// let three_secs = Duration::from_secs(3);
385 /// sleep(three_secs);
386 /// assert!(instant.elapsed() >= three_secs);
387 /// ```
388 #[must_use]
389 #[stable(feature = "time2", since = "1.8.0")]
390 pub fn elapsed(&self) -> Duration {
391 Instant::now() - *self
392 }
393
394 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
395 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
396 /// otherwise.
397 #[stable(feature = "time_checked_add", since = "1.34.0")]
398 pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
399 self.0.checked_add_duration(&duration).map(Instant)
400 }
401
402 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
403 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
404 /// otherwise.
405 #[stable(feature = "time_checked_add", since = "1.34.0")]
406 pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
407 self.0.checked_sub_duration(&duration).map(Instant)
408 }
409
410 // Used by platform specific `sleep_until` implementations such as the one used on Linux.
411 #[cfg_attr(
412 not(target_os = "linux"),
413 allow(unused, reason = "not every platform has a specific `sleep_until`")
414 )]
415 pub(crate) fn into_inner(self) -> time::Instant {
416 self.0
417 }
418}
419
420#[stable(feature = "time2", since = "1.8.0")]
421impl Add<Duration> for Instant {
422 type Output = Instant;
423
424 /// # Panics
425 ///
426 /// This function may panic if the resulting point in time cannot be represented by the
427 /// underlying data structure. See [`Instant::checked_add`] for a version without panic.
428 #[track_caller]
429 fn add(self, other: Duration) -> Instant {
430 self.checked_add(other).expect("overflow when adding duration to instant")
431 }
432}
433
434#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
435impl AddAssign<Duration> for Instant {
436 fn add_assign(&mut self, other: Duration) {
437 *self = *self + other;
438 }
439}
440
441#[stable(feature = "time2", since = "1.8.0")]
442impl Sub<Duration> for Instant {
443 type Output = Instant;
444
445 #[track_caller]
446 fn sub(self, other: Duration) -> Instant {
447 self.checked_sub(other).expect("overflow when subtracting duration from instant")
448 }
449}
450
451#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
452impl SubAssign<Duration> for Instant {
453 fn sub_assign(&mut self, other: Duration) {
454 *self = *self - other;
455 }
456}
457
458#[stable(feature = "time2", since = "1.8.0")]
459impl Sub<Instant> for Instant {
460 type Output = Duration;
461
462 /// Returns the amount of time elapsed from another instant to this one,
463 /// or zero duration if that instant is later than this one.
464 ///
465 /// # Panics
466 ///
467 /// Previous Rust versions panicked when `other` was later than `self`. Currently this
468 /// method saturates. Future versions may reintroduce the panic in some circumstances.
469 /// See [Monotonicity].
470 ///
471 /// [Monotonicity]: Instant#monotonicity
472 fn sub(self, other: Instant) -> Duration {
473 self.duration_since(other)
474 }
475}
476
477#[stable(feature = "time2", since = "1.8.0")]
478impl fmt::Debug for Instant {
479 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480 self.0.fmt(f)
481 }
482}
483
484impl SystemTime {
485 /// An anchor in time which can be used to create new `SystemTime` instances or
486 /// learn about where in time a `SystemTime` lies.
487 //
488 // NOTE! this documentation is duplicated, here and in std::time::UNIX_EPOCH.
489 // The two copies are not quite identical, because of the difference in naming.
490 ///
491 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
492 /// respect to the system clock. Using `duration_since` on an existing
493 /// `SystemTime` instance can tell how far away from this point in time a
494 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
495 /// `SystemTime` instance to represent another fixed point in time.
496 ///
497 /// `duration_since(UNIX_EPOCH).unwrap().as_secs()` returns
498 /// the number of non-leap seconds since the start of 1970 UTC.
499 /// This is a POSIX `time_t` (as a `u64`),
500 /// and is the same time representation as used in many Internet protocols.
501 ///
502 /// # Examples
503 ///
504 /// ```no_run
505 /// use std::time::SystemTime;
506 ///
507 /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
508 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
509 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
510 /// }
511 /// ```
512 #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
513 pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
514
515 /// Represents the maximum value representable by [`SystemTime`] on this platform.
516 ///
517 /// This value differs a lot between platforms, but it is always the case
518 /// that any positive addition of a [`Duration`], whose value is greater
519 /// than or equal to the time precision of the operating system, to
520 /// [`SystemTime::MAX`] will fail.
521 ///
522 /// # Examples
523 ///
524 /// ```no_run
525 /// #![feature(time_systemtime_limits)]
526 /// use std::time::{Duration, SystemTime};
527 ///
528 /// // Adding zero will change nothing.
529 /// assert_eq!(SystemTime::MAX.checked_add(Duration::ZERO), Some(SystemTime::MAX));
530 ///
531 /// // But adding just one second will already fail ...
532 /// //
533 /// // Keep in mind that this in fact may succeed, if the Duration is
534 /// // smaller than the time precision of the operating system, which
535 /// // happens to be 1ns on most operating systems, with Windows being the
536 /// // notable exception by using 100ns, hence why this example uses 1s.
537 /// assert_eq!(SystemTime::MAX.checked_add(Duration::new(1, 0)), None);
538 ///
539 /// // Utilize this for saturating arithmetic to improve error handling.
540 /// // In this case, we will use a certificate with a timestamp in the
541 /// // future as a practical example.
542 /// let configured_offset = Duration::from_secs(60 * 60 * 24);
543 /// let valid_after =
544 /// SystemTime::now()
545 /// .checked_add(configured_offset)
546 /// .unwrap_or(SystemTime::MAX);
547 /// ```
548 #[unstable(feature = "time_systemtime_limits", issue = "149067")]
549 pub const MAX: SystemTime = SystemTime(time::SystemTime::MAX);
550
551 /// Represents the minimum value representable by [`SystemTime`] on this platform.
552 ///
553 /// This value differs a lot between platforms, but it is always the case
554 /// that any positive subtraction of a [`Duration`] from, whose value is
555 /// greater than or equal to the time precision of the operating system, to
556 /// [`SystemTime::MIN`] will fail.
557 ///
558 /// Depending on the platform, this may be either less than or equal to
559 /// [`SystemTime::UNIX_EPOCH`], depending on whether the operating system
560 /// supports the representation of timestamps before the Unix epoch or not.
561 /// However, it is always guaranteed that a [`SystemTime::UNIX_EPOCH`] fits
562 /// between a [`SystemTime::MIN`] and [`SystemTime::MAX`].
563 ///
564 /// # Examples
565 ///
566 /// ```
567 /// #![feature(time_systemtime_limits)]
568 /// use std::time::{Duration, SystemTime};
569 ///
570 /// // Subtracting zero will change nothing.
571 /// assert_eq!(SystemTime::MIN.checked_sub(Duration::ZERO), Some(SystemTime::MIN));
572 ///
573 /// // But subtracting just one second will already fail.
574 /// //
575 /// // Keep in mind that this in fact may succeed, if the Duration is
576 /// // smaller than the time precision of the operating system, which
577 /// // happens to be 1ns on most operating systems, with Windows being the
578 /// // notable exception by using 100ns, hence why this example uses 1s.
579 /// assert_eq!(SystemTime::MIN.checked_sub(Duration::new(1, 0)), None);
580 ///
581 /// // Utilize this for saturating arithmetic to improve error handling.
582 /// // In this case, we will use a cache expiry as a practical example.
583 /// let configured_expiry = Duration::from_secs(60 * 3);
584 /// let expiry_threshold =
585 /// SystemTime::now()
586 /// .checked_sub(configured_expiry)
587 /// .unwrap_or(SystemTime::MIN);
588 /// ```
589 #[unstable(feature = "time_systemtime_limits", issue = "149067")]
590 pub const MIN: SystemTime = SystemTime(time::SystemTime::MIN);
591
592 /// Returns the system time corresponding to "now".
593 ///
594 /// # Examples
595 ///
596 /// ```
597 /// use std::time::SystemTime;
598 ///
599 /// let sys_time = SystemTime::now();
600 /// ```
601 #[must_use]
602 #[stable(feature = "time2", since = "1.8.0")]
603 pub fn now() -> SystemTime {
604 SystemTime(time::SystemTime::now())
605 }
606
607 /// Returns the amount of time elapsed from an earlier point in time.
608 ///
609 /// This function may fail because measurements taken earlier are not
610 /// guaranteed to always be before later measurements (due to anomalies such
611 /// as the system clock being adjusted either forwards or backwards).
612 /// [`Instant`] can be used to measure elapsed time without this risk of failure.
613 ///
614 /// If successful, <code>[Ok]\([Duration])</code> is returned where the duration represents
615 /// the amount of time elapsed from the specified measurement to this one.
616 ///
617 /// Returns an [`Err`] if `earlier` is later than `self`, and the error
618 /// contains how far from `self` the time is.
619 ///
620 /// # Examples
621 ///
622 /// ```no_run
623 /// use std::time::SystemTime;
624 ///
625 /// let sys_time = SystemTime::now();
626 /// let new_sys_time = SystemTime::now();
627 /// let difference = new_sys_time.duration_since(sys_time)
628 /// .expect("Clock may have gone backwards");
629 /// println!("{difference:?}");
630 /// ```
631 #[stable(feature = "time2", since = "1.8.0")]
632 pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError> {
633 self.0.sub_time(&earlier.0).map_err(SystemTimeError)
634 }
635
636 /// Returns the difference from this system time to the
637 /// current clock time.
638 ///
639 /// This function may fail as the underlying system clock is susceptible to
640 /// drift and updates (e.g., the system clock could go backwards), so this
641 /// function might not always succeed. If successful, <code>[Ok]\([Duration])</code> is
642 /// returned where the duration represents the amount of time elapsed from
643 /// this time measurement to the current time.
644 ///
645 /// To measure elapsed time reliably, use [`Instant`] instead.
646 ///
647 /// Returns an [`Err`] if `self` is later than the current system time, and
648 /// the error contains how far from the current system time `self` is.
649 ///
650 /// # Examples
651 ///
652 /// ```no_run
653 /// use std::thread::sleep;
654 /// use std::time::{Duration, SystemTime};
655 ///
656 /// let sys_time = SystemTime::now();
657 /// let one_sec = Duration::from_secs(1);
658 /// sleep(one_sec);
659 /// assert!(sys_time.elapsed().unwrap() >= one_sec);
660 /// ```
661 #[stable(feature = "time2", since = "1.8.0")]
662 pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
663 SystemTime::now().duration_since(*self)
664 }
665
666 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
667 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
668 /// otherwise.
669 ///
670 /// In the case that the `duration` is smaller than the time precision of the operating
671 /// system, `Some(self)` will be returned.
672 #[stable(feature = "time_checked_add", since = "1.34.0")]
673 pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
674 self.0.checked_add_duration(&duration).map(SystemTime)
675 }
676
677 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
678 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
679 /// otherwise.
680 ///
681 /// In the case that the `duration` is smaller than the time precision of the operating
682 /// system, `Some(self)` will be returned.
683 #[stable(feature = "time_checked_add", since = "1.34.0")]
684 pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
685 self.0.checked_sub_duration(&duration).map(SystemTime)
686 }
687
688 /// Saturating [`SystemTime`] addition, computing `self + duration`,
689 /// returning [`SystemTime::MAX`] if overflow occurred.
690 ///
691 /// In the case that the `duration` is smaller than the time precision of
692 /// the operating system, `self` will be returned.
693 #[unstable(feature = "time_saturating_systemtime", issue = "151199")]
694 pub fn saturating_add(&self, duration: Duration) -> SystemTime {
695 self.checked_add(duration).unwrap_or(SystemTime::MAX)
696 }
697
698 /// Saturating [`SystemTime`] subtraction, computing `self - duration`,
699 /// returning [`SystemTime::MIN`] if overflow occurred.
700 ///
701 /// In the case that the `duration` is smaller than the time precision of
702 /// the operating system, `self` will be returned.
703 #[unstable(feature = "time_saturating_systemtime", issue = "151199")]
704 pub fn saturating_sub(&self, duration: Duration) -> SystemTime {
705 self.checked_sub(duration).unwrap_or(SystemTime::MIN)
706 }
707
708 /// Saturating computation of time elapsed from an earlier point in time,
709 /// returning [`Duration::ZERO`] in the case that `earlier` is later or
710 /// equal to `self`.
711 ///
712 /// # Examples
713 ///
714 /// ```no_run
715 /// #![feature(time_saturating_systemtime)]
716 /// use std::time::{Duration, SystemTime};
717 ///
718 /// let now = SystemTime::now();
719 /// let prev = now.saturating_sub(Duration::new(1, 0));
720 ///
721 /// // now - prev should return non-zero.
722 /// assert_eq!(now.saturating_duration_since(prev), Duration::new(1, 0));
723 /// assert!(now.duration_since(prev).is_ok());
724 ///
725 /// // prev - now should return zero (and fail with the non-saturating).
726 /// assert_eq!(prev.saturating_duration_since(now), Duration::ZERO);
727 /// assert!(prev.duration_since(now).is_err());
728 ///
729 /// // now - now should return zero (and work with the non-saturating).
730 /// assert_eq!(now.saturating_duration_since(now), Duration::ZERO);
731 /// assert!(now.duration_since(now).is_ok());
732 /// ```
733 #[unstable(feature = "time_saturating_systemtime", issue = "151199")]
734 pub fn saturating_duration_since(&self, earlier: SystemTime) -> Duration {
735 self.duration_since(earlier).unwrap_or(Duration::ZERO)
736 }
737}
738
739#[stable(feature = "time2", since = "1.8.0")]
740impl Add<Duration> for SystemTime {
741 type Output = SystemTime;
742
743 /// # Panics
744 ///
745 /// This function may panic if the resulting point in time cannot be represented by the
746 /// underlying data structure. See [`SystemTime::checked_add`] for a version without panic.
747 #[track_caller]
748 fn add(self, dur: Duration) -> SystemTime {
749 self.checked_add(dur).expect("overflow when adding duration to `SystemTime`")
750 }
751}
752
753#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
754impl AddAssign<Duration> for SystemTime {
755 fn add_assign(&mut self, other: Duration) {
756 *self = *self + other;
757 }
758}
759
760#[stable(feature = "time2", since = "1.8.0")]
761impl Sub<Duration> for SystemTime {
762 type Output = SystemTime;
763
764 #[track_caller]
765 fn sub(self, dur: Duration) -> SystemTime {
766 self.checked_sub(dur).expect("overflow when subtracting duration from `SystemTime`")
767 }
768}
769
770#[stable(feature = "time_augmented_assignment", since = "1.9.0")]
771impl SubAssign<Duration> for SystemTime {
772 fn sub_assign(&mut self, other: Duration) {
773 *self = *self - other;
774 }
775}
776
777#[stable(feature = "time2", since = "1.8.0")]
778impl fmt::Debug for SystemTime {
779 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
780 self.0.fmt(f)
781 }
782}
783
784/// An anchor in time which can be used to create new `SystemTime` instances or
785/// learn about where in time a `SystemTime` lies.
786//
787// NOTE! this documentation is duplicated, here and in SystemTime::UNIX_EPOCH.
788// The two copies are not quite identical, because of the difference in naming.
789///
790/// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
791/// respect to the system clock. Using `duration_since` on an existing
792/// [`SystemTime`] instance can tell how far away from this point in time a
793/// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
794/// [`SystemTime`] instance to represent another fixed point in time.
795///
796/// `duration_since(UNIX_EPOCH).unwrap().as_secs()` returns
797/// the number of non-leap seconds since the start of 1970 UTC.
798/// This is a POSIX `time_t` (as a `u64`),
799/// and is the same time representation as used in many Internet protocols.
800///
801/// # Examples
802///
803/// ```no_run
804/// use std::time::{SystemTime, UNIX_EPOCH};
805///
806/// match SystemTime::now().duration_since(UNIX_EPOCH) {
807/// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
808/// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
809/// }
810/// ```
811#[stable(feature = "time2", since = "1.8.0")]
812pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
813
814impl SystemTimeError {
815 /// Returns the positive duration which represents how far forward the
816 /// second system time was from the first.
817 ///
818 /// A `SystemTimeError` is returned from the [`SystemTime::duration_since`]
819 /// and [`SystemTime::elapsed`] methods whenever the second system time
820 /// represents a point later in time than the `self` of the method call.
821 ///
822 /// # Examples
823 ///
824 /// ```no_run
825 /// use std::thread::sleep;
826 /// use std::time::{Duration, SystemTime};
827 ///
828 /// let sys_time = SystemTime::now();
829 /// sleep(Duration::from_secs(1));
830 /// let new_sys_time = SystemTime::now();
831 /// match sys_time.duration_since(new_sys_time) {
832 /// Ok(_) => {}
833 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
834 /// }
835 /// ```
836 #[must_use]
837 #[stable(feature = "time2", since = "1.8.0")]
838 pub fn duration(&self) -> Duration {
839 self.0
840 }
841}
842
843#[stable(feature = "time2", since = "1.8.0")]
844impl Error for SystemTimeError {}
845
846#[stable(feature = "time2", since = "1.8.0")]
847impl fmt::Display for SystemTimeError {
848 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
849 write!(f, "second time provided was later than self")
850 }
851}
852
853impl FromInner<time::SystemTime> for SystemTime {
854 fn from_inner(time: time::SystemTime) -> SystemTime {
855 SystemTime(time)
856 }
857}
858
859impl IntoInner<time::SystemTime> for SystemTime {
860 fn into_inner(self) -> time::SystemTime {
861 self.0
862 }
863}