Rust 语言中的时间单位及其使用方法

嗨咩狐(HimaFox)

time unit
2025-09-17
Rust 语言中的时间单位及其使用方法

Rust 时间单位及其使用方法

Rust 提供了强大的时间处理能力,适用于各种系统编程场景。本文将介绍 Rust 中的时间单位操作和最佳实践。

Rust 基本时间单位

Rust 的 std::time 模块提供了 Duration 类型,用于表示时间跨度。它包含秒和纳秒两个字段:

use std::time::Duration;

let one_second = Duration::from_secs(1);
let half_second = Duration::from_millis(500);

时间单位转换

Rust 可以轻松在不同时间单位间转换:

let duration = Duration::from_secs(2);
println!("毫秒: {}", duration.as_millis());  // 2000
println!("微秒: {}", duration.as_micros());  // 2000000
println!("纳秒: {}", duration.as_nanos());   // 2000000000

系统时间操作

获取和操作系统时间:

use std::time::{SystemTime, UNIX_EPOCH};

let now = SystemTime::now();
let since_epoch = now.duration_since(UNIX_EPOCH).unwrap();
println!("时间戳: {}秒", since_epoch.as_secs());

延迟和睡眠

实现延迟执行:

use std::thread;

thread::sleep(Duration::from_millis(100));  // 休眠100毫秒

chrono 库使用

chrono 库提供更丰富的时间处理功能:

use chrono::{Local, Duration};

let now = Local::now();
let tomorrow = now + Duration::days(1);
println!("明天: {}", tomorrow.format("%Y-%m-%d"));

时间格式化

格式化时间输出:

use chrono::Utc;

println!("当前时间: {}", Utc::now().format("%Y-%m-%d %H:%M:%S"));

性能比较

标准库和 chrono 的性能差异:

  • std::time 更轻量,适合基础操作
  • chrono 功能更全,但开销稍大

最佳实践

  1. 使用 checked_add 等安全方法防止溢出
  2. 在性能敏感场景优先使用 std::time
  3. 跨平台时注意时间精度差异
  4. 处理时间戳时考虑时区问题

示例代码

计算函数执行时间:

use std::time::Instant;

let start = Instant::now();
// 执行代码
let duration = start.elapsed();
println!("耗时: {:?}", duration);