1 //! Temporal quantification.
6 //! use std::time::Duration;
8 //! let five_seconds = Duration::new(5, 0);
9 //! // both declarations are equivalent
10 //! assert_eq!(Duration::new(5, 0), Duration::from_secs(5));
13 #![stable(feature = "time", since = "1.3.0")]
18 use ops::{Add, Sub, AddAssign, SubAssign};
20 use sys_common::FromInner;
21 use sys_common::mutex::Mutex;
23 #[stable(feature = "time", since = "1.3.0")]
24 pub use core::time::Duration;
26 #[unstable(feature = "duration_constants", issue = "57391")]
27 pub use core::time::{SECOND, MILLISECOND, MICROSECOND, NANOSECOND};
29 /// A measurement of a monotonically nondecreasing clock.
30 /// Opaque and useful only with `Duration`.
32 /// Instants are always guaranteed to be no less than any previously measured
33 /// instant when created, and are often useful for tasks such as measuring
34 /// benchmarks or timing how long an operation takes.
36 /// Note, however, that instants are not guaranteed to be **steady**. In other
37 /// words, each tick of the underlying clock may not be the same length (e.g.
38 /// some seconds may be longer than others). An instant may jump forwards or
39 /// experience time dilation (slow down or speed up), but it will never go
42 /// Instants are opaque types that can only be compared to one another. There is
43 /// no method to get "the number of seconds" from an instant. Instead, it only
44 /// allows measuring the duration between two instants (or comparing two
47 /// The size of an `Instant` struct may vary depending on the target operating
53 /// use std::time::{Duration, Instant};
54 /// use std::thread::sleep;
57 /// let now = Instant::now();
59 /// // we sleep for 2 seconds
60 /// sleep(Duration::new(2, 0));
62 /// println!("{}", now.elapsed().as_secs());
65 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
66 #[stable(feature = "time2", since = "1.8.0")]
67 pub struct Instant(time::Instant);
69 /// A measurement of the system clock, useful for talking to
70 /// external entities like the file system or other processes.
72 /// Distinct from the [`Instant`] type, this time measurement **is not
73 /// monotonic**. This means that you can save a file to the file system, then
74 /// save another file to the file system, **and the second file has a
75 /// `SystemTime` measurement earlier than the first**. In other words, an
76 /// operation that happens after another operation in real time may have an
77 /// earlier `SystemTime`!
79 /// Consequently, comparing two `SystemTime` instances to learn about the
80 /// duration between them returns a [`Result`] instead of an infallible [`Duration`]
81 /// to indicate that this sort of time drift may happen and needs to be handled.
83 /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
84 /// constant is provided in this module as an anchor in time to learn
85 /// information about a `SystemTime`. By calculating the duration from this
86 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
87 /// or perhaps some other string representation.
89 /// The size of a `SystemTime` struct may vary depending on the target operating
92 /// [`Instant`]: ../../std/time/struct.Instant.html
93 /// [`Result`]: ../../std/result/enum.Result.html
94 /// [`Duration`]: ../../std/time/struct.Duration.html
95 /// [`UNIX_EPOCH`]: ../../std/time/constant.UNIX_EPOCH.html
100 /// use std::time::{Duration, SystemTime};
101 /// use std::thread::sleep;
104 /// let now = SystemTime::now();
106 /// // we sleep for 2 seconds
107 /// sleep(Duration::new(2, 0));
108 /// match now.elapsed() {
111 /// println!("{}", elapsed.as_secs());
114 /// // an error occurred!
115 /// println!("Error: {:?}", e);
120 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
121 #[stable(feature = "time2", since = "1.8.0")]
122 pub struct SystemTime(time::SystemTime);
124 /// An error returned from the `duration_since` and `elapsed` methods on
125 /// `SystemTime`, used to learn how far in the opposite direction a system time
131 /// use std::thread::sleep;
132 /// use std::time::{Duration, SystemTime};
134 /// let sys_time = SystemTime::now();
135 /// sleep(Duration::from_secs(1));
136 /// let new_sys_time = SystemTime::now();
137 /// match sys_time.duration_since(new_sys_time) {
139 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
142 #[derive(Clone, Debug)]
143 #[stable(feature = "time2", since = "1.8.0")]
144 pub struct SystemTimeError(Duration);
147 /// Returns an instant corresponding to "now".
152 /// use std::time::Instant;
154 /// let now = Instant::now();
156 #[stable(feature = "time2", since = "1.8.0")]
157 pub fn now() -> Instant {
158 let os_now = time::Instant::now();
160 // And here we come upon a sad state of affairs. The whole point of
161 // `Instant` is that it's monotonically increasing. We've found in the
162 // wild, however, that it's not actually monotonically increasing for
163 // one reason or another. These appear to be OS and hardware level bugs,
164 // and there's not really a whole lot we can do about them. Here's a
165 // taste of what we've found:
167 // * #48514 - OpenBSD, x86_64
168 // * #49281 - linux arm64 and s390x
169 // * #51648 - windows, x86
170 // * #56560 - windows, x86_64, AWS
171 // * #56612 - windows, x86, vm (?)
172 // * #56940 - linux, arm64
173 // * https://bugzilla.mozilla.org/show_bug.cgi?id=1487778 - a similar
176 // It simply seems that this it just happens so that a lot in the wild
177 // we're seeing panics across various platforms where consecutive calls
178 // to `Instant::now`, such as via the `elapsed` function, are panicking
179 // as they're going backwards. Placed here is a last-ditch effort to try
180 // to fix things up. We keep a global "latest now" instance which is
181 // returned instead of what the OS says if the OS goes backwards.
183 // To hopefully mitigate the impact of this though a few platforms are
184 // whitelisted as "these at least haven't gone backwards yet".
185 if time::Instant::actually_monotonic() {
186 return Instant(os_now)
189 static LOCK: Mutex = Mutex::new();
190 static mut LAST_NOW: time::Instant = time::Instant::zero();
192 let _lock = LOCK.lock();
193 let now = cmp::max(LAST_NOW, os_now);
199 /// Returns the amount of time elapsed from another instant to this one.
203 /// This function will panic if `earlier` is later than `self`.
208 /// use std::time::{Duration, Instant};
209 /// use std::thread::sleep;
211 /// let now = Instant::now();
212 /// sleep(Duration::new(1, 0));
213 /// let new_now = Instant::now();
214 /// println!("{:?}", new_now.duration_since(now));
216 #[stable(feature = "time2", since = "1.8.0")]
217 pub fn duration_since(&self, earlier: Instant) -> Duration {
218 self.0.sub_instant(&earlier.0)
221 /// Returns the amount of time elapsed since this instant was created.
225 /// This function may panic if the current time is earlier than this
226 /// instant, which is something that can happen if an `Instant` is
227 /// produced synthetically.
232 /// use std::thread::sleep;
233 /// use std::time::{Duration, Instant};
235 /// let instant = Instant::now();
236 /// let three_secs = Duration::from_secs(3);
237 /// sleep(three_secs);
238 /// assert!(instant.elapsed() >= three_secs);
240 #[stable(feature = "time2", since = "1.8.0")]
241 pub fn elapsed(&self) -> Duration {
242 Instant::now() - *self
245 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
246 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
248 #[unstable(feature = "time_checked_add", issue = "55940")]
249 pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
250 self.0.checked_add_duration(&duration).map(|t| Instant(t))
253 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
254 /// `Instant` (which means it's inside the bounds of the underlying data structure), `None`
256 #[unstable(feature = "time_checked_add", issue = "55940")]
257 pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
258 self.0.checked_sub_duration(&duration).map(|t| Instant(t))
262 #[stable(feature = "time2", since = "1.8.0")]
263 impl Add<Duration> for Instant {
264 type Output = Instant;
268 /// This function may panic if the resulting point in time cannot be represented by the
269 /// underlying data structure. See [`checked_add`] for a version without panic.
271 /// [`checked_add`]: ../../std/time/struct.Instant.html#method.checked_add
272 fn add(self, other: Duration) -> Instant {
273 self.checked_add(other)
274 .expect("overflow when adding duration to instant")
278 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
279 impl AddAssign<Duration> for Instant {
280 fn add_assign(&mut self, other: Duration) {
281 *self = *self + other;
285 #[stable(feature = "time2", since = "1.8.0")]
286 impl Sub<Duration> for Instant {
287 type Output = Instant;
289 fn sub(self, other: Duration) -> Instant {
290 self.checked_sub(other)
291 .expect("overflow when subtracting duration from instant")
295 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
296 impl SubAssign<Duration> for Instant {
297 fn sub_assign(&mut self, other: Duration) {
298 *self = *self - other;
302 #[stable(feature = "time2", since = "1.8.0")]
303 impl Sub<Instant> for Instant {
304 type Output = Duration;
306 fn sub(self, other: Instant) -> Duration {
307 self.duration_since(other)
311 #[stable(feature = "time2", since = "1.8.0")]
312 impl fmt::Debug for Instant {
313 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
319 /// An anchor in time which can be used to create new `SystemTime` instances or
320 /// learn about where in time a `SystemTime` lies.
322 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
323 /// respect to the system clock. Using `duration_since` on an existing
324 /// `SystemTime` instance can tell how far away from this point in time a
325 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
326 /// `SystemTime` instance to represent another fixed point in time.
331 /// use std::time::SystemTime;
333 /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
334 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
335 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
338 #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
339 pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
341 /// Returns the system time corresponding to "now".
346 /// use std::time::SystemTime;
348 /// let sys_time = SystemTime::now();
350 #[stable(feature = "time2", since = "1.8.0")]
351 pub fn now() -> SystemTime {
352 SystemTime(time::SystemTime::now())
355 /// Returns the amount of time elapsed from an earlier point in time.
357 /// This function may fail because measurements taken earlier are not
358 /// guaranteed to always be before later measurements (due to anomalies such
359 /// as the system clock being adjusted either forwards or backwards).
361 /// If successful, [`Ok`]`(`[`Duration`]`)` is returned where the duration represents
362 /// the amount of time elapsed from the specified measurement to this one.
364 /// Returns an [`Err`] if `earlier` is later than `self`, and the error
365 /// contains how far from `self` the time is.
367 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
368 /// [`Duration`]: ../../std/time/struct.Duration.html
369 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
374 /// use std::time::SystemTime;
376 /// let sys_time = SystemTime::now();
377 /// let difference = sys_time.duration_since(sys_time)
378 /// .expect("SystemTime::duration_since failed");
379 /// println!("{:?}", difference);
381 #[stable(feature = "time2", since = "1.8.0")]
382 pub fn duration_since(&self, earlier: SystemTime)
383 -> Result<Duration, SystemTimeError> {
384 self.0.sub_time(&earlier.0).map_err(SystemTimeError)
387 /// Returns the amount of time elapsed since this system time was created.
389 /// This function may fail as the underlying system clock is susceptible to
390 /// drift and updates (e.g., the system clock could go backwards), so this
391 /// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is
392 /// returned where the duration represents the amount of time elapsed from
393 /// this time measurement to the current time.
395 /// Returns an [`Err`] if `self` is later than the current system time, and
396 /// the error contains how far from the current system time `self` is.
398 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
399 /// [`Duration`]: ../../std/time/struct.Duration.html
400 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
405 /// use std::thread::sleep;
406 /// use std::time::{Duration, SystemTime};
408 /// let sys_time = SystemTime::now();
409 /// let one_sec = Duration::from_secs(1);
411 /// assert!(sys_time.elapsed().unwrap() >= one_sec);
413 #[stable(feature = "time2", since = "1.8.0")]
414 pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
415 SystemTime::now().duration_since(*self)
418 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
419 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
421 #[unstable(feature = "time_checked_add", issue = "55940")]
422 pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
423 self.0.checked_add_duration(&duration).map(|t| SystemTime(t))
426 /// Returns `Some(t)` where `t` is the time `self - duration` if `t` can be represented as
427 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
429 #[unstable(feature = "time_checked_add", issue = "55940")]
430 pub fn checked_sub(&self, duration: Duration) -> Option<SystemTime> {
431 self.0.checked_sub_duration(&duration).map(|t| SystemTime(t))
435 #[stable(feature = "time2", since = "1.8.0")]
436 impl Add<Duration> for SystemTime {
437 type Output = SystemTime;
441 /// This function may panic if the resulting point in time cannot be represented by the
442 /// underlying data structure. See [`checked_add`] for a version without panic.
444 /// [`checked_add`]: ../../std/time/struct.SystemTime.html#method.checked_add
445 fn add(self, dur: Duration) -> SystemTime {
446 self.checked_add(dur)
447 .expect("overflow when adding duration to instant")
451 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
452 impl AddAssign<Duration> for SystemTime {
453 fn add_assign(&mut self, other: Duration) {
454 *self = *self + other;
458 #[stable(feature = "time2", since = "1.8.0")]
459 impl Sub<Duration> for SystemTime {
460 type Output = SystemTime;
462 fn sub(self, dur: Duration) -> SystemTime {
463 self.checked_sub(dur)
464 .expect("overflow when subtracting duration from instant")
468 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
469 impl SubAssign<Duration> for SystemTime {
470 fn sub_assign(&mut self, other: Duration) {
471 *self = *self - other;
475 #[stable(feature = "time2", since = "1.8.0")]
476 impl fmt::Debug for SystemTime {
477 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
482 /// An anchor in time which can be used to create new `SystemTime` instances or
483 /// learn about where in time a `SystemTime` lies.
485 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
486 /// respect to the system clock. Using `duration_since` on an existing
487 /// [`SystemTime`] instance can tell how far away from this point in time a
488 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
489 /// [`SystemTime`] instance to represent another fixed point in time.
491 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
496 /// use std::time::{SystemTime, UNIX_EPOCH};
498 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
499 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
500 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
503 #[stable(feature = "time2", since = "1.8.0")]
504 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
506 impl SystemTimeError {
507 /// Returns the positive duration which represents how far forward the
508 /// second system time was from the first.
510 /// A `SystemTimeError` is returned from the [`duration_since`] and [`elapsed`]
511 /// methods of [`SystemTime`] whenever the second system time represents a point later
512 /// in time than the `self` of the method call.
514 /// [`duration_since`]: ../../std/time/struct.SystemTime.html#method.duration_since
515 /// [`elapsed`]: ../../std/time/struct.SystemTime.html#method.elapsed
516 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
521 /// use std::thread::sleep;
522 /// use std::time::{Duration, SystemTime};
524 /// let sys_time = SystemTime::now();
525 /// sleep(Duration::from_secs(1));
526 /// let new_sys_time = SystemTime::now();
527 /// match sys_time.duration_since(new_sys_time) {
529 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
532 #[stable(feature = "time2", since = "1.8.0")]
533 pub fn duration(&self) -> Duration {
538 #[stable(feature = "time2", since = "1.8.0")]
539 impl Error for SystemTimeError {
540 fn description(&self) -> &str { "other time was not earlier than self" }
543 #[stable(feature = "time2", since = "1.8.0")]
544 impl fmt::Display for SystemTimeError {
545 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
546 write!(f, "second time provided was later than self")
550 impl FromInner<time::SystemTime> for SystemTime {
551 fn from_inner(time: time::SystemTime) -> SystemTime {
558 use super::{Instant, SystemTime, Duration, UNIX_EPOCH};
560 macro_rules! assert_almost_eq {
561 ($a:expr, $b:expr) => ({
562 let (a, b) = ($a, $b);
564 let (a, b) = if a > b {(a, b)} else {(b, a)};
565 assert!(a - Duration::new(0, 1000) <= b,
566 "{:?} is not almost equal to {:?}", a, b);
572 fn instant_monotonic() {
573 let a = Instant::now();
574 let b = Instant::now();
579 fn instant_elapsed() {
580 let a = Instant::now();
586 let a = Instant::now();
587 let b = Instant::now();
588 println!("a: {:?}", a);
589 println!("b: {:?}", b);
590 let dur = b.duration_since(a);
591 println!("dur: {:?}", dur);
592 assert_almost_eq!(b - dur, a);
593 assert_almost_eq!(a + dur, b);
595 let second = Duration::new(1, 0);
596 assert_almost_eq!(a - second + second, a);
597 assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a);
599 // checked_add_duration will not panic on overflow
600 let mut maybe_t = Some(Instant::now());
601 let max_duration = Duration::from_secs(u64::max_value());
602 // in case `Instant` can store `>= now + max_duration`.
604 maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
606 assert_eq!(maybe_t, None);
608 // checked_add_duration calculates the right time and will work for another year
609 let year = Duration::from_secs(60 * 60 * 24 * 365);
610 assert_eq!(a + year, a.checked_add(year).unwrap());
615 fn instant_duration_panic() {
616 let a = Instant::now();
617 (a - Duration::new(1, 0)).duration_since(a);
621 fn system_time_math() {
622 let a = SystemTime::now();
623 let b = SystemTime::now();
624 match b.duration_since(a) {
625 Ok(dur) if dur == Duration::new(0, 0) => {
626 assert_almost_eq!(a, b);
630 assert_almost_eq!(b - dur, a);
631 assert_almost_eq!(a + dur, b);
634 let dur = dur.duration();
636 assert_almost_eq!(b + dur, a);
637 assert_almost_eq!(a - dur, b);
641 let second = Duration::new(1, 0);
642 assert_almost_eq!(a.duration_since(a - second).unwrap(), second);
643 assert_almost_eq!(a.duration_since(a + second).unwrap_err()
644 .duration(), second);
646 assert_almost_eq!(a - second + second, a);
647 assert_almost_eq!(a.checked_sub(second).unwrap().checked_add(second).unwrap(), a);
649 // A difference of 80 and 800 years cannot fit inside a 32-bit time_t
650 if !(cfg!(unix) && ::mem::size_of::<::libc::time_t>() <= 4) {
651 let eighty_years = second * 60 * 60 * 24 * 365 * 80;
652 assert_almost_eq!(a - eighty_years + eighty_years, a);
653 assert_almost_eq!(a - (eighty_years * 10) + (eighty_years * 10), a);
656 let one_second_from_epoch = UNIX_EPOCH + Duration::new(1, 0);
657 let one_second_from_epoch2 = UNIX_EPOCH + Duration::new(0, 500_000_000)
658 + Duration::new(0, 500_000_000);
659 assert_eq!(one_second_from_epoch, one_second_from_epoch2);
661 // checked_add_duration will not panic on overflow
662 let mut maybe_t = Some(SystemTime::UNIX_EPOCH);
663 let max_duration = Duration::from_secs(u64::max_value());
664 // in case `SystemTime` can store `>= UNIX_EPOCH + max_duration`.
666 maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
668 assert_eq!(maybe_t, None);
670 // checked_add_duration calculates the right time and will work for another year
671 let year = Duration::from_secs(60 * 60 * 24 * 365);
672 assert_eq!(a + year, a.checked_add(year).unwrap());
676 fn system_time_elapsed() {
677 let a = SystemTime::now();
683 let ts = SystemTime::now();
684 let a = ts.duration_since(UNIX_EPOCH).unwrap();
685 let b = ts.duration_since(UNIX_EPOCH - Duration::new(1, 0)).unwrap();
687 assert_eq!(b - a, Duration::new(1, 0));
689 let thirty_years = Duration::new(1, 0) * 60 * 60 * 24 * 365 * 30;
691 // Right now for CI this test is run in an emulator, and apparently the
692 // aarch64 emulator's sense of time is that we're still living in the
695 // Otherwise let's assume that we're all running computers later than
697 if !cfg!(target_arch = "aarch64") {
698 assert!(a > thirty_years);
701 // let's assume that we're all running computers earlier than 2090.
702 // Should give us ~70 years to fix this!
703 let hundred_twenty_years = thirty_years * 4;
704 assert!(a < hundred_twenty_years);