1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Temporal quantification.
16 //! use std::time::Duration;
18 //! let five_seconds = Duration::new(5, 0);
19 //! // both declarations are equivalent
20 //! assert_eq!(Duration::new(5, 0), Duration::from_secs(5));
23 #![stable(feature = "time", since = "1.3.0")]
27 use ops::{Add, Sub, AddAssign, SubAssign};
29 use sys_common::FromInner;
31 #[stable(feature = "time", since = "1.3.0")]
32 pub use core::time::Duration;
34 /// A measurement of a monotonically nondecreasing clock.
35 /// Opaque and useful only with `Duration`.
37 /// Instants are always guaranteed to be no less than any previously measured
38 /// instant when created, and are often useful for tasks such as measuring
39 /// benchmarks or timing how long an operation takes.
41 /// Note, however, that instants are not guaranteed to be **steady**. In other
42 /// words, each tick of the underlying clock may not be the same length (e.g.
43 /// some seconds may be longer than others). An instant may jump forwards or
44 /// experience time dilation (slow down or speed up), but it will never go
47 /// Instants are opaque types that can only be compared to one another. There is
48 /// no method to get "the number of seconds" from an instant. Instead, it only
49 /// allows measuring the duration between two instants (or comparing two
52 /// The size of an `Instant` struct may vary depending on the target operating
58 /// use std::time::{Duration, Instant};
59 /// use std::thread::sleep;
62 /// let now = Instant::now();
64 /// // we sleep for 2 seconds
65 /// sleep(Duration::new(2, 0));
67 /// println!("{}", now.elapsed().as_secs());
70 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
71 #[stable(feature = "time2", since = "1.8.0")]
72 pub struct Instant(time::Instant);
74 /// A measurement of the system clock, useful for talking to
75 /// external entities like the file system or other processes.
77 /// Distinct from the [`Instant`] type, this time measurement **is not
78 /// monotonic**. This means that you can save a file to the file system, then
79 /// save another file to the file system, **and the second file has a
80 /// `SystemTime` measurement earlier than the first**. In other words, an
81 /// operation that happens after another operation in real time may have an
82 /// earlier `SystemTime`!
84 /// Consequently, comparing two `SystemTime` instances to learn about the
85 /// duration between them returns a [`Result`] instead of an infallible [`Duration`]
86 /// to indicate that this sort of time drift may happen and needs to be handled.
88 /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
89 /// constant is provided in this module as an anchor in time to learn
90 /// information about a `SystemTime`. By calculating the duration from this
91 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
92 /// or perhaps some other string representation.
94 /// The size of a `SystemTime` struct may vary depending on the target operating
97 /// [`Instant`]: ../../std/time/struct.Instant.html
98 /// [`Result`]: ../../std/result/enum.Result.html
99 /// [`Duration`]: ../../std/time/struct.Duration.html
100 /// [`UNIX_EPOCH`]: ../../std/time/constant.UNIX_EPOCH.html
105 /// use std::time::{Duration, SystemTime};
106 /// use std::thread::sleep;
109 /// let now = SystemTime::now();
111 /// // we sleep for 2 seconds
112 /// sleep(Duration::new(2, 0));
113 /// match now.elapsed() {
116 /// println!("{}", elapsed.as_secs());
119 /// // an error occurred!
120 /// println!("Error: {:?}", e);
125 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
126 #[stable(feature = "time2", since = "1.8.0")]
127 pub struct SystemTime(time::SystemTime);
129 /// An error returned from the `duration_since` and `elapsed` methods on
130 /// `SystemTime`, used to learn how far in the opposite direction a system time
136 /// use std::thread::sleep;
137 /// use std::time::{Duration, SystemTime};
139 /// let sys_time = SystemTime::now();
140 /// sleep(Duration::from_secs(1));
141 /// let new_sys_time = SystemTime::now();
142 /// match sys_time.duration_since(new_sys_time) {
144 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
147 #[derive(Clone, Debug)]
148 #[stable(feature = "time2", since = "1.8.0")]
149 pub struct SystemTimeError(Duration);
152 /// Returns an instant corresponding to "now".
157 /// use std::time::Instant;
159 /// let now = Instant::now();
161 #[stable(feature = "time2", since = "1.8.0")]
162 pub fn now() -> Instant {
163 Instant(time::Instant::now())
166 /// Returns the amount of time elapsed from another instant to this one.
170 /// This function will panic if `earlier` is later than `self`.
175 /// use std::time::{Duration, Instant};
176 /// use std::thread::sleep;
178 /// let now = Instant::now();
179 /// sleep(Duration::new(1, 0));
180 /// let new_now = Instant::now();
181 /// println!("{:?}", new_now.duration_since(now));
183 #[stable(feature = "time2", since = "1.8.0")]
184 pub fn duration_since(&self, earlier: Instant) -> Duration {
185 self.0.sub_instant(&earlier.0)
188 /// Returns the amount of time elapsed since this instant was created.
192 /// This function may panic if the current time is earlier than this
193 /// instant, which is something that can happen if an `Instant` is
194 /// produced synthetically.
199 /// use std::thread::sleep;
200 /// use std::time::{Duration, Instant};
202 /// let instant = Instant::now();
203 /// let three_secs = Duration::from_secs(3);
204 /// sleep(three_secs);
205 /// assert!(instant.elapsed() >= three_secs);
207 #[stable(feature = "time2", since = "1.8.0")]
208 pub fn elapsed(&self) -> Duration {
209 Instant::now() - *self
213 #[stable(feature = "time2", since = "1.8.0")]
214 impl Add<Duration> for Instant {
215 type Output = Instant;
217 fn add(self, other: Duration) -> Instant {
218 Instant(self.0.add_duration(&other))
222 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
223 impl AddAssign<Duration> for Instant {
224 fn add_assign(&mut self, other: Duration) {
225 *self = *self + other;
229 #[stable(feature = "time2", since = "1.8.0")]
230 impl Sub<Duration> for Instant {
231 type Output = Instant;
233 fn sub(self, other: Duration) -> Instant {
234 Instant(self.0.sub_duration(&other))
238 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
239 impl SubAssign<Duration> for Instant {
240 fn sub_assign(&mut self, other: Duration) {
241 *self = *self - other;
245 #[stable(feature = "time2", since = "1.8.0")]
246 impl Sub<Instant> for Instant {
247 type Output = Duration;
249 fn sub(self, other: Instant) -> Duration {
250 self.duration_since(other)
254 #[stable(feature = "time2", since = "1.8.0")]
255 impl fmt::Debug for Instant {
256 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
262 /// An anchor in time which can be used to create new `SystemTime` instances or
263 /// learn about where in time a `SystemTime` lies.
265 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
266 /// respect to the system clock. Using `duration_since` on an existing
267 /// `SystemTime` instance can tell how far away from this point in time a
268 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
269 /// `SystemTime` instance to represent another fixed point in time.
274 /// use std::time::SystemTime;
276 /// match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
277 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
278 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
281 #[stable(feature = "assoc_unix_epoch", since = "1.28.0")]
282 pub const UNIX_EPOCH: SystemTime = UNIX_EPOCH;
284 /// Returns the system time corresponding to "now".
289 /// use std::time::SystemTime;
291 /// let sys_time = SystemTime::now();
293 #[stable(feature = "time2", since = "1.8.0")]
294 pub fn now() -> SystemTime {
295 SystemTime(time::SystemTime::now())
298 /// Returns the amount of time elapsed from an earlier point in time.
300 /// This function may fail because measurements taken earlier are not
301 /// guaranteed to always be before later measurements (due to anomalies such
302 /// as the system clock being adjusted either forwards or backwards).
304 /// If successful, [`Ok`]`(`[`Duration`]`)` is returned where the duration represents
305 /// the amount of time elapsed from the specified measurement to this one.
307 /// Returns an [`Err`] if `earlier` is later than `self`, and the error
308 /// contains how far from `self` the time is.
310 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
311 /// [`Duration`]: ../../std/time/struct.Duration.html
312 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
317 /// use std::time::SystemTime;
319 /// let sys_time = SystemTime::now();
320 /// let difference = sys_time.duration_since(sys_time)
321 /// .expect("SystemTime::duration_since failed");
322 /// println!("{:?}", difference);
324 #[stable(feature = "time2", since = "1.8.0")]
325 pub fn duration_since(&self, earlier: SystemTime)
326 -> Result<Duration, SystemTimeError> {
327 self.0.sub_time(&earlier.0).map_err(SystemTimeError)
330 /// Returns the amount of time elapsed since this system time was created.
332 /// This function may fail as the underlying system clock is susceptible to
333 /// drift and updates (e.g., the system clock could go backwards), so this
334 /// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is
335 /// returned where the duration represents the amount of time elapsed from
336 /// this time measurement to the current time.
338 /// Returns an [`Err`] if `self` is later than the current system time, and
339 /// the error contains how far from the current system time `self` is.
341 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
342 /// [`Duration`]: ../../std/time/struct.Duration.html
343 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
348 /// use std::thread::sleep;
349 /// use std::time::{Duration, SystemTime};
351 /// let sys_time = SystemTime::now();
352 /// let one_sec = Duration::from_secs(1);
354 /// assert!(sys_time.elapsed().unwrap() >= one_sec);
356 #[stable(feature = "time2", since = "1.8.0")]
357 pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
358 SystemTime::now().duration_since(*self)
361 /// Returns `Some(t)` where `t` is the time `self + duration` if `t` can be represented as
362 /// `SystemTime` (which means it's inside the bounds of the underlying data structure), `None`
364 #[unstable(feature = "time_checked_add", issue = "55940")]
365 pub fn checked_add(&self, duration: Duration) -> Option<SystemTime> {
366 self.0.checked_add_duration(&duration).map(|t| SystemTime(t))
370 #[stable(feature = "time2", since = "1.8.0")]
371 impl Add<Duration> for SystemTime {
372 type Output = SystemTime;
374 fn add(self, dur: Duration) -> SystemTime {
375 SystemTime(self.0.add_duration(&dur))
379 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
380 impl AddAssign<Duration> for SystemTime {
381 fn add_assign(&mut self, other: Duration) {
382 *self = *self + other;
386 #[stable(feature = "time2", since = "1.8.0")]
387 impl Sub<Duration> for SystemTime {
388 type Output = SystemTime;
390 fn sub(self, dur: Duration) -> SystemTime {
391 SystemTime(self.0.sub_duration(&dur))
395 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
396 impl SubAssign<Duration> for SystemTime {
397 fn sub_assign(&mut self, other: Duration) {
398 *self = *self - other;
402 #[stable(feature = "time2", since = "1.8.0")]
403 impl fmt::Debug for SystemTime {
404 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
409 /// An anchor in time which can be used to create new `SystemTime` instances or
410 /// learn about where in time a `SystemTime` lies.
412 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
413 /// respect to the system clock. Using `duration_since` on an existing
414 /// [`SystemTime`] instance can tell how far away from this point in time a
415 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
416 /// [`SystemTime`] instance to represent another fixed point in time.
418 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
423 /// use std::time::{SystemTime, UNIX_EPOCH};
425 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
426 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
427 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
430 #[stable(feature = "time2", since = "1.8.0")]
431 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
433 impl SystemTimeError {
434 /// Returns the positive duration which represents how far forward the
435 /// second system time was from the first.
437 /// A `SystemTimeError` is returned from the [`duration_since`] and [`elapsed`]
438 /// methods of [`SystemTime`] whenever the second system time represents a point later
439 /// in time than the `self` of the method call.
441 /// [`duration_since`]: ../../std/time/struct.SystemTime.html#method.duration_since
442 /// [`elapsed`]: ../../std/time/struct.SystemTime.html#method.elapsed
443 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
448 /// use std::thread::sleep;
449 /// use std::time::{Duration, SystemTime};
451 /// let sys_time = SystemTime::now();
452 /// sleep(Duration::from_secs(1));
453 /// let new_sys_time = SystemTime::now();
454 /// match sys_time.duration_since(new_sys_time) {
456 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
459 #[stable(feature = "time2", since = "1.8.0")]
460 pub fn duration(&self) -> Duration {
465 #[stable(feature = "time2", since = "1.8.0")]
466 impl Error for SystemTimeError {
467 fn description(&self) -> &str { "other time was not earlier than self" }
470 #[stable(feature = "time2", since = "1.8.0")]
471 impl fmt::Display for SystemTimeError {
472 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
473 write!(f, "second time provided was later than self")
477 impl FromInner<time::SystemTime> for SystemTime {
478 fn from_inner(time: time::SystemTime) -> SystemTime {
485 use super::{Instant, SystemTime, Duration, UNIX_EPOCH};
487 macro_rules! assert_almost_eq {
488 ($a:expr, $b:expr) => ({
489 let (a, b) = ($a, $b);
491 let (a, b) = if a > b {(a, b)} else {(b, a)};
492 assert!(a - Duration::new(0, 1000) <= b,
493 "{:?} is not almost equal to {:?}", a, b);
499 fn instant_monotonic() {
500 let a = Instant::now();
501 let b = Instant::now();
506 fn instant_elapsed() {
507 let a = Instant::now();
513 let a = Instant::now();
514 let b = Instant::now();
515 println!("a: {:?}", a);
516 println!("b: {:?}", b);
517 let dur = b.duration_since(a);
518 println!("dur: {:?}", dur);
519 assert_almost_eq!(b - dur, a);
520 assert_almost_eq!(a + dur, b);
522 let second = Duration::new(1, 0);
523 assert_almost_eq!(a - second + second, a);
528 fn instant_duration_panic() {
529 let a = Instant::now();
530 (a - Duration::new(1, 0)).duration_since(a);
534 fn system_time_math() {
535 let a = SystemTime::now();
536 let b = SystemTime::now();
537 match b.duration_since(a) {
538 Ok(dur) if dur == Duration::new(0, 0) => {
539 assert_almost_eq!(a, b);
543 assert_almost_eq!(b - dur, a);
544 assert_almost_eq!(a + dur, b);
547 let dur = dur.duration();
549 assert_almost_eq!(b + dur, a);
550 assert_almost_eq!(a - dur, b);
554 let second = Duration::new(1, 0);
555 assert_almost_eq!(a.duration_since(a - second).unwrap(), second);
556 assert_almost_eq!(a.duration_since(a + second).unwrap_err()
557 .duration(), second);
559 assert_almost_eq!(a - second + second, a);
561 // A difference of 80 and 800 years cannot fit inside a 32-bit time_t
562 if !(cfg!(unix) && ::mem::size_of::<::libc::time_t>() <= 4) {
563 let eighty_years = second * 60 * 60 * 24 * 365 * 80;
564 assert_almost_eq!(a - eighty_years + eighty_years, a);
565 assert_almost_eq!(a - (eighty_years * 10) + (eighty_years * 10), a);
568 let one_second_from_epoch = UNIX_EPOCH + Duration::new(1, 0);
569 let one_second_from_epoch2 = UNIX_EPOCH + Duration::new(0, 500_000_000)
570 + Duration::new(0, 500_000_000);
571 assert_eq!(one_second_from_epoch, one_second_from_epoch2);
573 // checked_add_duration will not panic on overflow
574 let mut maybe_t = Some(SystemTime::UNIX_EPOCH);
575 let max_duration = Duration::from_secs(u64::max_value());
576 // in case `SystemTime` can store `>= UNIX_EPOCH + max_duration`.
578 maybe_t = maybe_t.and_then(|t| t.checked_add(max_duration));
580 assert_eq!(maybe_t, None);
582 // checked_add_duration calculates the right time and will work for another year
583 let year = Duration::from_secs(60 * 60 * 24 * 365);
584 assert_eq!(a + year, a.checked_add(year).unwrap());
588 fn system_time_elapsed() {
589 let a = SystemTime::now();
595 let ts = SystemTime::now();
596 let a = ts.duration_since(UNIX_EPOCH).unwrap();
597 let b = ts.duration_since(UNIX_EPOCH - Duration::new(1, 0)).unwrap();
599 assert_eq!(b - a, Duration::new(1, 0));
601 let thirty_years = Duration::new(1, 0) * 60 * 60 * 24 * 365 * 30;
603 // Right now for CI this test is run in an emulator, and apparently the
604 // aarch64 emulator's sense of time is that we're still living in the
607 // Otherwise let's assume that we're all running computers later than
609 if !cfg!(target_arch = "aarch64") {
610 assert!(a > thirty_years);
613 // let's assume that we're all running computers earlier than 2090.
614 // Should give us ~70 years to fix this!
615 let hundred_twenty_years = thirty_years * 4;
616 assert!(a < hundred_twenty_years);