std::time
最後更新
表示時間長度、量測經過的時間,以及取得系統時鐘的目前時刻。
這個模組做什麼
std::time 只有三個主角,各管一件事:| 型別 | 代表 | 典型用途 |
|---|---|---|
Duration | 一段時間長度(例如 1.5 秒) | 逾時設定、sleep、計算差值 |
Instant | 單調時鐘(monotonic clock)上的一個時間點 | 量測程式跑了多久 |
SystemTime | 系統時鐘(牆上時鐘)上的一個時間點 | 時間戳記、檔案修改時間 |
Instant 像碼表:只會往前走,不受使用者調整時鐘影響,但沒辦法換算成「幾月幾號」。SystemTime 像牆上的時鐘:對應真實日期,但可能被校時而往回跳。量測耗時用 Instant,記錄「什麼時候發生」用 SystemTime。標準庫不提供日期格式化與時區處理,要顯示
2024-01-01 12:00 這類格式需要第三方 crate。匯入
- 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。簽名:
- pub const fn from_secs(secs: u64) -> Duration;
- pub const fn from_millis(millis: u64) -> Duration;
- pub const fn as_secs(&self) -> u64;
- pub const fn as_millis(&self) -> u128;
- pub fn as_secs_f64(&self) -> f64;
注意:
as_secs 會捨去小數部分(1500ms 得到 1)。from_secs_f64 傳入負數、NaN 或溢位的值會 panic。範例:
- use std::time::Duration;
- fn main() {
- let a = Duration::from_secs(90);
- let b = Duration::from_millis(1500);
- let c = Duration::from_secs_f64(0.25);
- println!("{:?} {:?} {:?}", a, b, c);
- println!("a: {} secs, {} mins", a.as_secs(), a.as_secs() / 60);
- println!("b: {} ms, secs part {} + {} ms", b.as_millis(), b.as_secs(), b.subsec_millis());
- println!("c as f64: {}", c.as_secs_f64());
- println!("zero? {}", Duration::ZERO.is_zero());
- }
輸出:
- 90s 1.5s 250ms
- a: 90 secs, 1 mins
- b: 1500 ms, secs part 1 + 500 ms
- c as f64: 0.25
- zero? true
Duration 的運算:加減乘除與安全版本
Duration 支援 +、-、*、/(乘除的另一邊是 u32)以及比較。因為不能是負數,減法有兩種安全版本:checked_sub 結果為負時回傳 None,saturating_sub 則停在 Duration::ZERO。try_from_secs_f64(Rust 1.66 起)是不會 panic 的建立方式。簽名:
- pub const fn checked_sub(self, rhs: Duration) -> Option<Duration>;
- pub const fn saturating_sub(self, rhs: Duration) -> Duration;
- pub fn try_from_secs_f64(secs: f64) -> Result<Duration, TryFromFloatSecsError>;
注意:直接用
- 時,若結果為負會 panic;+ 與 * 溢位也會 panic。不確定大小關係時用 checked_ 或 saturating_ 版本。範例:
- use std::time::Duration;
- fn main() {
- let timeout = Duration::from_secs(5);
- let spent = Duration::from_millis(3200);
- println!("sum: {:?}", timeout + spent);
- println!("x3: {:?}", spent * 3);
- println!("half: {:?}", timeout / 2);
- println!("left: {:?}", timeout.checked_sub(spent));
- println!("over: {:?}", spent.checked_sub(timeout));
- println!("saturating: {:?}", spent.saturating_sub(timeout));
- println!("max: {:?}", timeout.max(spent));
- let bad = Duration::try_from_secs_f64(-1.0);
- println!("negative secs is error: {}", bad.is_err());
- }
輸出:
- sum: 8.2s
- x3: 9.6s
- half: 2.5s
- left: Some(1.8s)
- over: None
- saturating: 0ns
- max: 5s
- negative secs is error: true
Instant::now 與 elapsed:量測耗時
在工作開始前呼叫
Instant::now(),結束後呼叫 elapsed(),就得到中間經過的 Duration。這是量測函式效能最簡單的方式。範例中的 thread::sleep 見 std::thread。簽名:
- pub fn now() -> Instant;
- pub fn elapsed(&self) -> Duration;
注意:
sleep 保證至少睡指定的時間,實際可能更久;量測結果也會受系統負載影響。要比較效能時請多跑幾次,並以 --release(或 rustc -O)編譯。範例:
- use std::thread;
- use std::time::{Duration, Instant};
- fn slow_work() -> u64 {
- thread::sleep(Duration::from_millis(50));
- (1..=1000).sum()
- }
- fn main() {
- let start = Instant::now();
- let result = slow_work();
- let elapsed = start.elapsed();
- println!("result = {}", result);
- println!("took at least 50ms: {}", elapsed >= Duration::from_millis(50));
- println!("took under 5s: {}", elapsed < Duration::from_secs(5));
- }
輸出:
- result = 500500
- took at least 50ms: true
- took under 5s: true
Instant 的運算:截止時間與先後比較
Instant 加上 Duration 得到未來的時間點,適合寫「最多重試到某個截止時間」的迴圈。兩個 Instant 可以直接比較大小,duration_since 算出差距。簽名:
- pub fn duration_since(&self, earlier: Instant) -> Duration;
- pub fn checked_duration_since(&self, earlier: Instant) -> Option<Duration>;
- pub fn saturating_duration_since(&self, earlier: Instant) -> Duration;
注意:
a.duration_since(b) 在 b 比 a 晚時目前會回傳零而不是 panic,但官方不保證未來維持這個行為;順序不確定時明確使用 checked_duration_since 或 saturating_duration_since。範例:
- use std::thread;
- use std::time::{Duration, Instant};
- fn main() {
- let start = Instant::now();
- let deadline = start + Duration::from_millis(30);
- let mut rounds = 0;
- while Instant::now() < deadline {
- rounds += 1;
- thread::sleep(Duration::from_millis(5));
- }
- println!("looped at least once: {}", rounds > 0);
- let later = Instant::now();
- println!("later >= deadline: {}", later >= deadline);
- println!("later - start >= 30ms: {}", later.duration_since(start) >= Duration::from_millis(30));
- println!("start - later (checked): {:?}", start.checked_duration_since(later));
- println!("start - later (saturating): {:?}", start.saturating_duration_since(later));
- }
輸出:
- looped at least once: true
- later >= deadline: true
- later - start >= 30ms: true
- start - later (checked): None
- 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。簽名:
- pub const UNIX_EPOCH: SystemTime;
- pub fn now() -> SystemTime;
- pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, SystemTimeError>;
範例:
- use std::time::{Duration, SystemTime, UNIX_EPOCH};
- fn main() {
- let now = SystemTime::now();
- let since = now.duration_since(UNIX_EPOCH).expect("clock is after 1970");
- println!("after 2023-11-14: {}", since.as_secs() > 1_700_000_000);
- let billennium = UNIX_EPOCH + Duration::from_secs(1_000_000_000);
- let ts = billennium.duration_since(UNIX_EPOCH).unwrap();
- println!("unix seconds: {}", ts.as_secs());
- println!("unix millis: {}", ts.as_millis());
- let days = ts.as_secs() / 86_400;
- println!("days since epoch: {}", days);
- }
輸出:
- after 2023-11-14: true
- unix seconds: 1000000000
- unix millis: 1000000000000
- days since epoch: 11574
SystemTimeError:時鐘往回跳
系統時鐘可能被使用者或網路校時調整,所以
SystemTime 之間的差可能是「負的」。duration_since 與 elapsed 因此回傳 Result:順序顛倒時得到 SystemTimeError,可用 duration() 取得差了多少。簽名:
- pub fn elapsed(&self) -> Result<Duration, SystemTimeError>;
- pub fn duration(&self) -> Duration;
注意:不要用
SystemTime 量測耗時,時鐘跳動會讓結果錯誤甚至回傳 Err;量測請用 Instant。範例:
- use std::time::{Duration, SystemTime, UNIX_EPOCH};
- fn main() {
- let early = UNIX_EPOCH + Duration::from_secs(100);
- let late = UNIX_EPOCH + Duration::from_secs(160);
- println!("late - early: {:?}", late.duration_since(early));
- match early.duration_since(late) {
- Ok(d) => println!("forward: {:?}", d),
- Err(e) => println!("went backwards by {:?}: {}", e.duration(), e),
- }
- let past = SystemTime::now() - Duration::from_secs(3600);
- match past.elapsed() {
- Ok(d) => println!("elapsed >= 1h: {}", d >= Duration::from_secs(3600)),
- Err(e) => println!("clock moved: {}", e),
- }
- }
輸出:
- late - early: Ok(60s)
- went backwards by 60s: second time provided was later than self
- elapsed >= 1h: true
重點整理
Duration是時間長度,不能為負;減法用checked_sub/saturating_sub最安全- 量測耗時用
Instant::now()加elapsed(),它不受校時影響 - 時間戳記用
SystemTime::now().duration_since(UNIX_EPOCH) SystemTime的差值回傳Result,因為時鐘可能往回跳- 日期格式化與時區不在標準庫內