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 self::duration::Duration;
36 /// A measurement of a monotonically nondecreasing clock.
37 /// Opaque and useful only with `Duration`.
39 /// Instants are always guaranteed to be no less than any previously measured
40 /// instant when created, and are often useful for tasks such as measuring
41 /// benchmarks or timing how long an operation takes.
43 /// Note, however, that instants are not guaranteed to be **steady**. In other
44 /// words, each tick of the underlying clock may not be the same length (e.g.
45 /// some seconds may be longer than others). An instant may jump forwards or
46 /// experience time dilation (slow down or speed up), but it will never go
49 /// Instants are opaque types that can only be compared to one another. There is
50 /// no method to get "the number of seconds" from an instant. Instead, it only
51 /// allows measuring the duration between two instants (or comparing two
57 /// use std::time::{Duration, Instant};
58 /// use std::thread::sleep;
61 /// let now = Instant::now();
63 /// // we sleep for 2 seconds
64 /// sleep(Duration::new(2, 0));
66 /// println!("{}", now.elapsed().as_secs());
69 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
70 #[stable(feature = "time2", since = "1.8.0")]
71 pub struct Instant(time::Instant);
73 /// A measurement of the system clock, useful for talking to
74 /// external entities like the file system or other processes.
76 /// Distinct from the [`Instant`] type, this time measurement **is not
77 /// monotonic**. This means that you can save a file to the file system, then
78 /// save another file to the file system, **and the second file has a
79 /// `SystemTime` measurement earlier than the first**. In other words, an
80 /// operation that happens after another operation in real time may have an
81 /// earlier `SystemTime`!
83 /// Consequently, comparing two `SystemTime` instances to learn about the
84 /// duration between them returns a [`Result`] instead of an infallible [`Duration`]
85 /// to indicate that this sort of time drift may happen and needs to be handled.
87 /// Although a `SystemTime` cannot be directly inspected, the [`UNIX_EPOCH`]
88 /// constant is provided in this module as an anchor in time to learn
89 /// information about a `SystemTime`. By calculating the duration from this
90 /// fixed point in time, a `SystemTime` can be converted to a human-readable time,
91 /// or perhaps some other string representation.
93 /// [`Instant`]: ../../std/time/struct.Instant.html
94 /// [`Result`]: ../../std/result/enum.Result.html
95 /// [`Duration`]: ../../std/time/struct.Duration.html
96 /// [`UNIX_EPOCH`]: ../../std/time/constant.UNIX_EPOCH.html
101 /// use std::time::{Duration, SystemTime};
102 /// use std::thread::sleep;
105 /// let now = SystemTime::now();
107 /// // we sleep for 2 seconds
108 /// sleep(Duration::new(2, 0));
109 /// match now.elapsed() {
112 /// println!("{}", elapsed.as_secs());
115 /// // an error occurred!
116 /// println!("Error: {:?}", e);
121 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
122 #[stable(feature = "time2", since = "1.8.0")]
123 pub struct SystemTime(time::SystemTime);
125 /// An error returned from the `duration_since` and `elapsed` methods on
126 /// `SystemTime`, used to learn how far in the opposite direction a system time
132 /// use std::thread::sleep;
133 /// use std::time::{Duration, SystemTime};
135 /// let sys_time = SystemTime::now();
136 /// sleep(Duration::from_secs(1));
137 /// let new_sys_time = SystemTime::now();
138 /// match sys_time.duration_since(new_sys_time) {
140 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
143 #[derive(Clone, Debug)]
144 #[stable(feature = "time2", since = "1.8.0")]
145 pub struct SystemTimeError(Duration);
148 /// Returns an instant corresponding to "now".
153 /// use std::time::Instant;
155 /// let now = Instant::now();
157 #[stable(feature = "time2", since = "1.8.0")]
158 pub fn now() -> Instant {
159 Instant(time::Instant::now())
162 /// Returns the amount of time elapsed from another instant to this one.
166 /// This function will panic if `earlier` is later than `self`.
171 /// use std::time::{Duration, Instant};
172 /// use std::thread::sleep;
174 /// let now = Instant::now();
175 /// sleep(Duration::new(1, 0));
176 /// let new_now = Instant::now();
177 /// println!("{:?}", new_now.duration_since(now));
179 #[stable(feature = "time2", since = "1.8.0")]
180 pub fn duration_since(&self, earlier: Instant) -> Duration {
181 self.0.sub_instant(&earlier.0)
184 /// Returns the amount of time elapsed since this instant was created.
188 /// This function may panic if the current time is earlier than this
189 /// instant, which is something that can happen if an `Instant` is
190 /// produced synthetically.
195 /// use std::thread::sleep;
196 /// use std::time::{Duration, Instant};
198 /// let instant = Instant::now();
199 /// let three_secs = Duration::from_secs(3);
200 /// sleep(three_secs);
201 /// assert!(instant.elapsed() >= three_secs);
203 #[stable(feature = "time2", since = "1.8.0")]
204 pub fn elapsed(&self) -> Duration {
205 Instant::now() - *self
209 #[stable(feature = "time2", since = "1.8.0")]
210 impl Add<Duration> for Instant {
211 type Output = Instant;
213 fn add(self, other: Duration) -> Instant {
214 Instant(self.0.add_duration(&other))
218 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
219 impl AddAssign<Duration> for Instant {
220 fn add_assign(&mut self, other: Duration) {
221 *self = *self + other;
225 #[stable(feature = "time2", since = "1.8.0")]
226 impl Sub<Duration> for Instant {
227 type Output = Instant;
229 fn sub(self, other: Duration) -> Instant {
230 Instant(self.0.sub_duration(&other))
234 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
235 impl SubAssign<Duration> for Instant {
236 fn sub_assign(&mut self, other: Duration) {
237 *self = *self - other;
241 #[stable(feature = "time2", since = "1.8.0")]
242 impl Sub<Instant> for Instant {
243 type Output = Duration;
245 fn sub(self, other: Instant) -> Duration {
246 self.duration_since(other)
250 #[stable(feature = "time2", since = "1.8.0")]
251 impl fmt::Debug for Instant {
252 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
258 /// Returns the system time corresponding to "now".
263 /// use std::time::SystemTime;
265 /// let sys_time = SystemTime::now();
267 #[stable(feature = "time2", since = "1.8.0")]
268 pub fn now() -> SystemTime {
269 SystemTime(time::SystemTime::now())
272 /// Returns the amount of time elapsed from an earlier point in time.
274 /// This function may fail because measurements taken earlier are not
275 /// guaranteed to always be before later measurements (due to anomalies such
276 /// as the system clock being adjusted either forwards or backwards).
278 /// If successful, [`Ok`]`(`[`Duration`]`)` is returned where the duration represents
279 /// the amount of time elapsed from the specified measurement to this one.
281 /// Returns an [`Err`] if `earlier` is later than `self`, and the error
282 /// contains how far from `self` the time is.
284 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
285 /// [`Duration`]: ../../std/time/struct.Duration.html
286 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
291 /// use std::time::SystemTime;
293 /// let sys_time = SystemTime::now();
294 /// let difference = sys_time.duration_since(sys_time)
295 /// .expect("SystemTime::duration_since failed");
296 /// println!("{:?}", difference);
298 #[stable(feature = "time2", since = "1.8.0")]
299 pub fn duration_since(&self, earlier: SystemTime)
300 -> Result<Duration, SystemTimeError> {
301 self.0.sub_time(&earlier.0).map_err(SystemTimeError)
304 /// Returns the amount of time elapsed since this system time was created.
306 /// This function may fail as the underlying system clock is susceptible to
307 /// drift and updates (e.g. the system clock could go backwards), so this
308 /// function may not always succeed. If successful, [`Ok`]`(`[`Duration`]`)` is
309 /// returned where the duration represents the amount of time elapsed from
310 /// this time measurement to the current time.
312 /// Returns an [`Err`] if `self` is later than the current system time, and
313 /// the error contains how far from the current system time `self` is.
315 /// [`Ok`]: ../../std/result/enum.Result.html#variant.Ok
316 /// [`Duration`]: ../../std/time/struct.Duration.html
317 /// [`Err`]: ../../std/result/enum.Result.html#variant.Err
322 /// use std::thread::sleep;
323 /// use std::time::{Duration, SystemTime};
325 /// let sys_time = SystemTime::now();
326 /// let one_sec = Duration::from_secs(1);
328 /// assert!(sys_time.elapsed().unwrap() >= one_sec);
330 #[stable(feature = "time2", since = "1.8.0")]
331 pub fn elapsed(&self) -> Result<Duration, SystemTimeError> {
332 SystemTime::now().duration_since(*self)
336 #[stable(feature = "time2", since = "1.8.0")]
337 impl Add<Duration> for SystemTime {
338 type Output = SystemTime;
340 fn add(self, dur: Duration) -> SystemTime {
341 SystemTime(self.0.add_duration(&dur))
345 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
346 impl AddAssign<Duration> for SystemTime {
347 fn add_assign(&mut self, other: Duration) {
348 *self = *self + other;
352 #[stable(feature = "time2", since = "1.8.0")]
353 impl Sub<Duration> for SystemTime {
354 type Output = SystemTime;
356 fn sub(self, dur: Duration) -> SystemTime {
357 SystemTime(self.0.sub_duration(&dur))
361 #[stable(feature = "time_augmented_assignment", since = "1.9.0")]
362 impl SubAssign<Duration> for SystemTime {
363 fn sub_assign(&mut self, other: Duration) {
364 *self = *self - other;
368 #[stable(feature = "time2", since = "1.8.0")]
369 impl fmt::Debug for SystemTime {
370 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
375 /// An anchor in time which can be used to create new `SystemTime` instances or
376 /// learn about where in time a `SystemTime` lies.
378 /// This constant is defined to be "1970-01-01 00:00:00 UTC" on all systems with
379 /// respect to the system clock. Using `duration_since` on an existing
380 /// [`SystemTime`] instance can tell how far away from this point in time a
381 /// measurement lies, and using `UNIX_EPOCH + duration` can be used to create a
382 /// [`SystemTime`] instance to represent another fixed point in time.
384 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
389 /// use std::time::{SystemTime, UNIX_EPOCH};
391 /// match SystemTime::now().duration_since(UNIX_EPOCH) {
392 /// Ok(n) => println!("1970-01-01 00:00:00 UTC was {} seconds ago!", n.as_secs()),
393 /// Err(_) => panic!("SystemTime before UNIX EPOCH!"),
396 #[stable(feature = "time2", since = "1.8.0")]
397 pub const UNIX_EPOCH: SystemTime = SystemTime(time::UNIX_EPOCH);
399 impl SystemTimeError {
400 /// Returns the positive duration which represents how far forward the
401 /// second system time was from the first.
403 /// A `SystemTimeError` is returned from the [`duration_since`] and [`elapsed`]
404 /// methods of [`SystemTime`] whenever the second system time represents a point later
405 /// in time than the `self` of the method call.
407 /// [`duration_since`]: ../../std/time/struct.SystemTime.html#method.duration_since
408 /// [`elapsed`]: ../../std/time/struct.SystemTime.html#method.elapsed
409 /// [`SystemTime`]: ../../std/time/struct.SystemTime.html
414 /// use std::thread::sleep;
415 /// use std::time::{Duration, SystemTime};
417 /// let sys_time = SystemTime::now();
418 /// sleep(Duration::from_secs(1));
419 /// let new_sys_time = SystemTime::now();
420 /// match sys_time.duration_since(new_sys_time) {
422 /// Err(e) => println!("SystemTimeError difference: {:?}", e.duration()),
425 #[stable(feature = "time2", since = "1.8.0")]
426 pub fn duration(&self) -> Duration {
431 #[stable(feature = "time2", since = "1.8.0")]
432 impl Error for SystemTimeError {
433 fn description(&self) -> &str { "other time was not earlier than self" }
436 #[stable(feature = "time2", since = "1.8.0")]
437 impl fmt::Display for SystemTimeError {
438 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
439 write!(f, "second time provided was later than self")
443 impl FromInner<time::SystemTime> for SystemTime {
444 fn from_inner(time: time::SystemTime) -> SystemTime {
451 use super::{Instant, SystemTime, Duration, UNIX_EPOCH};
453 macro_rules! assert_almost_eq {
454 ($a:expr, $b:expr) => ({
455 let (a, b) = ($a, $b);
457 let (a, b) = if a > b {(a, b)} else {(b, a)};
458 assert!(a - Duration::new(0, 100) <= b);
464 fn instant_monotonic() {
465 let a = Instant::now();
466 let b = Instant::now();
471 fn instant_elapsed() {
472 let a = Instant::now();
478 let a = Instant::now();
479 let b = Instant::now();
480 let dur = b.duration_since(a);
481 assert_almost_eq!(b - dur, a);
482 assert_almost_eq!(a + dur, b);
484 let second = Duration::new(1, 0);
485 assert_almost_eq!(a - second + second, a);
490 fn instant_duration_panic() {
491 let a = Instant::now();
492 (a - Duration::new(1, 0)).duration_since(a);
496 fn system_time_math() {
497 let a = SystemTime::now();
498 let b = SystemTime::now();
499 match b.duration_since(a) {
500 Ok(dur) if dur == Duration::new(0, 0) => {
501 assert_almost_eq!(a, b);
505 assert_almost_eq!(b - dur, a);
506 assert_almost_eq!(a + dur, b);
509 let dur = dur.duration();
511 assert_almost_eq!(b + dur, a);
512 assert_almost_eq!(a - dur, b);
516 let second = Duration::new(1, 0);
517 assert_almost_eq!(a.duration_since(a - second).unwrap(), second);
518 assert_almost_eq!(a.duration_since(a + second).unwrap_err()
519 .duration(), second);
521 assert_almost_eq!(a - second + second, a);
523 // A difference of 80 and 800 years cannot fit inside a 32-bit time_t
524 if !(cfg!(unix) && ::mem::size_of::<::libc::time_t>() <= 4) {
525 let eighty_years = second * 60 * 60 * 24 * 365 * 80;
526 assert_almost_eq!(a - eighty_years + eighty_years, a);
527 assert_almost_eq!(a - (eighty_years * 10) + (eighty_years * 10), a);
530 let one_second_from_epoch = UNIX_EPOCH + Duration::new(1, 0);
531 let one_second_from_epoch2 = UNIX_EPOCH + Duration::new(0, 500_000_000)
532 + Duration::new(0, 500_000_000);
533 assert_eq!(one_second_from_epoch, one_second_from_epoch2);
537 fn system_time_elapsed() {
538 let a = SystemTime::now();
544 let ts = SystemTime::now();
545 let a = ts.duration_since(UNIX_EPOCH).unwrap();
546 let b = ts.duration_since(UNIX_EPOCH - Duration::new(1, 0)).unwrap();
548 assert_eq!(b - a, Duration::new(1, 0));
550 let thirty_years = Duration::new(1, 0) * 60 * 60 * 24 * 365 * 30;
552 // Right now for CI this test is run in an emulator, and apparently the
553 // aarch64 emulator's sense of time is that we're still living in the
556 // Otherwise let's assume that we're all running computers later than
558 if !cfg!(target_arch = "aarch64") {
559 assert!(a > thirty_years);
562 // let's assume that we're all running computers earlier than 2090.
563 // Should give us ~70 years to fix this!
564 let hundred_twenty_years = thirty_years * 4;
565 assert!(a < hundred_twenty_years);