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