std::time

最後更新


表示時間長度、量測經過的時間,以及取得系統時鐘的目前時刻。

這個模組做什麼


std::time 只有三個主角,各管一件事:
型別代表典型用途
Duration一段時間長度(例如 1.5 秒)逾時設定、sleep、計算差值
Instant單調時鐘(monotonic clock)上的一個時間點量測程式跑了多久
SystemTime系統時鐘(牆上時鐘)上的一個時間點時間戳記、檔案修改時間

Instant 像碼表:只會往前走,不受使用者調整時鐘影響,但沒辦法換算成「幾月幾號」。SystemTime 像牆上的時鐘:對應真實日期,但可能被校時而往回跳。量測耗時用 Instant,記錄「什麼時候發生」用 SystemTime。
標準庫不提供日期格式化與時區處理,要顯示 2024-01-01 12:00 這類格式需要第三方 crate。

匯入


  1. use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

本頁範例不印出實際時刻或耗時數字(每次執行都不同),而是印出比較的結果。

常用 API


Duration:建立與讀取時間長度


Duration 內部以「秒 + 奈秒」儲存,不會是負數。用 from_secs、from_millis、from_micros、from_nanos、from_secs_f64 建立;用 as_secs、as_millis、as_secs_f64 讀出總量,subsec_millis 則取得不滿一秒的部分。{:?} 會印出易讀的格式,如 1.5s。
簽名:
  1. pub const fn from_secs(secs: u64) -> Duration;
  2. pub const fn from_millis(millis: u64) -> Duration;
  3. pub const fn as_secs(&self) -> u64;
  4. pub const fn as_millis(&self) -> u128;
  5. pub fn as_secs_f64(&self) -> f64;

注意:as_secs 會捨去小數部分(1500ms 得到 1)。from_secs_f64 傳入負數、NaN 或溢位的值會 panic。
範例:
  1. use std::time::Duration;
  2. fn main() {
  3. let a = Duration::from_secs(90);
  4. let b = Duration::from_millis(1500);
  5. let c = Duration::from_secs_f64(0.25);
  6. println!("{:?} {:?} {:?}", a, b, c);
  7. println!("a: {} secs, {} mins", a.as_secs(), a.as_secs() / 60);
  8. println!("b: {} ms, secs part {} + {} ms", b.as_millis(), b.as_secs(), b.subsec_millis());
  9. println!("c as f64: {}", c.as_secs_f64());
  10. println!("zero? {}", Duration::ZERO.is_zero());
  11. }

輸出:
  1. 90s 1.5s 250ms
  2. a: 90 secs, 1 mins
  3. b: 1500 ms, secs part 1 + 500 ms
  4. c as f64: 0.25
  5. zero? true

Duration 的運算:加減乘除與安全版本


Duration 支援 +、-、*、/(乘除的另一邊是 u32)以及比較。因為不能是負數,減法有兩種安全版本:checked_sub 結果為負時回傳 None,saturating_sub 則停在 Duration::ZERO。try_from_secs_f64(Rust 1.66 起)是不會 panic 的建立方式。
簽名:
  1. pub const fn checked_sub(self, rhs: Duration) -> Option<Duration>;
  2. pub const fn saturating_sub(self, rhs: Duration) -> Duration;
  3. pub fn try_from_secs_f64(secs: f64) -> Result<Duration, TryFromFloatSecsError>;

注意:直接用 - 時,若結果為負會 panic;+ 與 * 溢位也會 panic。不確定大小關係時用 checked_ 或 saturating_ 版本。
範例:
  1. use std::time::Duration;
  2. fn main() {
  3. let timeout = Duration::from_secs(5);
  4. let spent = Duration::from_millis(3200);
  5. println!("sum: {:?}", timeout + spent);
  6. println!("x3: {:?}", spent * 3);
  7. println!("half: {:?}", timeout / 2);
  8. println!("left: {:?}", timeout.checked_sub(spent));
  9. println!("over: {:?}", spent.checked_sub(timeout));
  10. println!("saturating: {:?}", spent.saturating_sub(timeout));
  11. println!("max: {:?}", timeout.max(spent));
  12. let bad = Duration::try_from_secs_f64(-1.0);
  13. println!("negative secs is error: {}", bad.is_err());
  14. }

輸出:
  1. sum: 8.2s
  2. x3: 9.6s
  3. half: 2.5s
  4. left: Some(1.8s)
  5. over: None
  6. saturating: 0ns
  7. max: 5s
  8. negative secs is error: true

Instant::now 與 elapsed:量測耗時


在工作開始前呼叫 Instant::now(),結束後呼叫 elapsed(),就得到中間經過的 Duration。這是量測函式效能最簡單的方式。範例中的 thread::sleep 見 std::thread。
簽名:
  1. pub fn now() -> Instant;
  2. pub fn elapsed(&self) -> Duration;

注意:sleep 保證至少睡指定的時間,實際可能更久;量測結果也會受系統負載影響。要比較效能時請多跑幾次,並以 --release(或 rustc -O)編譯。
範例:
  1. use std::thread;
  2. use std::time::{Duration, Instant};
  3. fn slow_work() -> u64 {
  4. thread::sleep(Duration::from_millis(50));
  5. (1..=1000).sum()
  6. }
  7. fn main() {
  8. let start = Instant::now();
  9. let result = slow_work();
  10. let elapsed = start.elapsed();
  11. println!("result = {}", result);
  12. println!("took at least 50ms: {}", elapsed >= Duration::from_millis(50));
  13. println!("took under 5s: {}", elapsed < Duration::from_secs(5));
  14. }

輸出:
  1. result = 500500
  2. took at least 50ms: true
  3. took under 5s: true

Instant 的運算:截止時間與先後比較


Instant 加上 Duration 得到未來的時間點,適合寫「最多重試到某個截止時間」的迴圈。兩個 Instant 可以直接比較大小,duration_since 算出差距。
簽名:
  1. pub fn duration_since(&self, earlier: Instant) -> Duration;
  2. pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration>;
  3. pub fn saturating_duration_since(&self, earlier: Instant) -> Duration;

注意:a.duration_since(b) 在 b 比 a 晚時目前會回傳零而不是 panic,但官方不保證未來維持這個行為;順序不確定時明確使用 checked_duration_since 或 saturating_duration_since。
範例:
  1. use std::thread;
  2. use std::time::{Duration, Instant};
  3. fn main() {
  4. let start = Instant::now();
  5. let deadline = start + Duration::from_millis(30);
  6. let mut rounds = 0;
  7. while Instant::now() < deadline {
  8. rounds += 1;
  9. thread::sleep(Duration::from_millis(5));
  10. }
  11. println!("looped at least once: {}", rounds > 0);
  12. let later = Instant::now();
  13. println!("later >= deadline: {}", later >= deadline);
  14. println!("later - start >= 30ms: {}", later.duration_since(start) >= Duration::from_millis(30));
  15. println!("start - later (checked): {:?}", start.checked_duration_since(later));
  16. println!("start - later (saturating): {:?}", start.saturating_duration_since(later));
  17. }

輸出:
  1. looped at least once: true
  2. later >= deadline: true
  3. later - start >= 30ms: true
  4. start - later (checked): None
  5. start - later (saturating): 0ns

SystemTime 與 UNIX_EPOCH:時間戳記


SystemTime::now() 取得系統時鐘的目前時刻。它本身無法直接印成數字,通常會換算成「距離 UNIX 紀元(1970-01-01 00:00:00 UTC)過了多久」,也就是 UNIX 時間戳記(timestamp),常用於資料庫、API、日誌。
UNIX_EPOCH 是代表那個起點的常數,UNIX_EPOCH + Duration 可以從時間戳記還原出 SystemTime。檔案的修改時間(std::fs 的 metadata().modified())也是 SystemTime。
簽名:
  1. pub const UNIX_EPOCH: SystemTime;
  2. pub fn now() -> SystemTime;
  3. pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError>;

範例:
  1. use std::time::{Duration, SystemTime, UNIX_EPOCH};
  2. fn main() {
  3. let now = SystemTime::now();
  4. let since = now.duration_since(UNIX_EPOCH).expect("clock is after 1970");
  5. println!("after 2023-11-14: {}", since.as_secs() > 1_700_000_000);
  6. let billennium = UNIX_EPOCH + Duration::from_secs(1_000_000_000);
  7. let ts = billennium.duration_since(UNIX_EPOCH).unwrap();
  8. println!("unix seconds: {}", ts.as_secs());
  9. println!("unix millis: {}", ts.as_millis());
  10. let days = ts.as_secs() / 86_400;
  11. println!("days since epoch: {}", days);
  12. }

輸出:
  1. after 2023-11-14: true
  2. unix seconds: 1000000000
  3. unix millis: 1000000000000
  4. days since epoch: 11574

SystemTimeError:時鐘往回跳


系統時鐘可能被使用者或網路校時調整,所以 SystemTime 之間的差可能是「負的」。duration_since 與 elapsed 因此回傳 Result:順序顛倒時得到 SystemTimeError,可用 duration() 取得差了多少。
簽名:
  1. pub fn elapsed(&self) -> Result<Duration, SystemTimeError>;
  2. pub fn duration(&self) -> Duration;

注意:不要用 SystemTime 量測耗時,時鐘跳動會讓結果錯誤甚至回傳 Err;量測請用 Instant。
範例:
  1. use std::time::{Duration, SystemTime, UNIX_EPOCH};
  2. fn main() {
  3. let early = UNIX_EPOCH + Duration::from_secs(100);
  4. let late = UNIX_EPOCH + Duration::from_secs(160);
  5. println!("late - early: {:?}", late.duration_since(early));
  6. match early.duration_since(late) {
  7. Ok(d) => println!("forward: {:?}", d),
  8. Err(e) => println!("went backwards by {:?}: {}", e.duration(), e),
  9. }
  10. let past = SystemTime::now() - Duration::from_secs(3600);
  11. match past.elapsed() {
  12. Ok(d) => println!("elapsed >= 1h: {}", d >= Duration::from_secs(3600)),
  13. Err(e) => println!("clock moved: {}", e),
  14. }
  15. }

輸出:
  1. late - early: Ok(60s)
  2. went backwards by 60s: second time provided was later than self
  3. elapsed >= 1h: true

重點整理


  • Duration 是時間長度,不能為負;減法用 checked_sub/saturating_sub 最安全
  • 量測耗時用 Instant::now() 加 elapsed(),它不受校時影響
  • 時間戳記用 SystemTime::now().duration_since(UNIX_EPOCH)
  • SystemTime 的差值回傳 Result,因為時鐘可能往回跳
  • 日期格式化與時區不在標準庫內