【time-rs】Duration 结构体详解

这是一个 Rust 时间库中的 Duration 结构体实现,提供高精度的时间跨度表示。

1. 主要特性

  • 纳秒级精度:由整秒和纳秒部分组成
  • 支持负值 :与标准库的 std::time::Duration 不同,支持负时间间隔
  • 安全边界检查 :使用 RangedI32 确保纳秒值在有效范围(-999,999,999 到 999,999,999)

2. 核心结构

rust 复制代码
pub struct Duration {
    seconds: i64,           // 整秒数
    nanoseconds: Nanoseconds, // 纳秒部分(带范围检查)
    padding: Padding,       // 用于编译器优化(niche value optimization)
}

3. 时间单位常量

提供了常用时间单位的预定义常量:

rust 复制代码
// 基本单位
pub const NANOSECOND: Self = Self::nanoseconds(1);
pub const MICROSECOND: Self = Self::microseconds(1);
pub const MILLISECOND: Self = Self::milliseconds(1);
pub const SECOND: Self = Self::seconds(1);
pub const MINUTE: Self = Self::minutes(1);
pub const HOUR: Self = Self::hours(1);
pub const DAY: Self = Self::days(1);
pub const WEEK: Self = Self::weeks(1);

// 特殊值
pub const ZERO: Self = Self::seconds(0);
pub const MIN: Self = Self::new_ranged(i64::MIN, Nanoseconds::MIN);
pub const MAX: Self = Self::new_ranged(i64::MAX, Nanoseconds::MAX);

4. 构造函数

多种构造方式:

rust 复制代码
// 从秒和纳秒创建
let d1 = Duration::new(1, 500_000_000); // 1.5秒

// 从时间单位创建
let d2 = Duration::hours(2);    // 2小时
let d3 = Duration::minutes(30); // 30分钟

// 从浮点数创建
let d4 = Duration::seconds_f64(1.5); // 1.5秒
let d5 = Duration::seconds_f32(0.5); // 0.5秒

// 从小单位创建
let d6 = Duration::milliseconds(1500); // 1500毫秒
let d7 = Duration::microseconds(500);  // 500微秒
let d8 = Duration::nanoseconds(100);   // 100纳秒

5. 查询方法

获取整数值

rust 复制代码
let duration = Duration::hours(2) + Duration::minutes(30);

duration.whole_hours();    // 2
duration.whole_minutes();  // 150
duration.whole_seconds();  // 9000
duration.whole_days();     // 0

获取小数部分

rust 复制代码
let duration = Duration::seconds(1) + Duration::milliseconds(500);

duration.as_seconds_f64();      // 1.5
duration.as_seconds_f32();      // 1.5
duration.subsec_milliseconds(); // 500
duration.subsec_microseconds(); // 500000
duration.subsec_nanoseconds();  // 500000000

6. 属性检查

rust 复制代码
let pos = Duration::seconds(5);
let neg = Duration::seconds(-5);
let zero = Duration::ZERO;

pos.is_positive();  // true
pos.is_negative();  // false
pos.is_zero();      // false

neg.is_positive();  // false
neg.is_negative();  // true
neg.is_zero();      // false

zero.is_zero();     // true

7. 数学运算

加法

rust 复制代码
let d1 = Duration::seconds(5);
let d2 = Duration::seconds(3);

// 普通加法(可能panic)
let sum = d1 + d2; // 8秒

// 检查溢出的加法
let checked = d1.checked_add(d2); // Some(8秒)

// 饱和加法
let saturated = Duration::MAX.saturating_add(d2); // Duration::MAX

减法

rust 复制代码
let d1 = Duration::seconds(5);
let d2 = Duration::seconds(3);

let diff = d1 - d2;        // 2秒
let neg_diff = d2 - d1;    // -2秒
let checked = d1.checked_sub(d2); // Some(2秒)

乘除法

rust 复制代码
let d = Duration::seconds(10);

let multiplied = d * 2;    // 20秒
let divided = d / 2;       // 5秒
let float_mul = d * 1.5;   // 15秒
let float_div = d / 2.5;   // 4秒

取反

rust 复制代码
let d = Duration::seconds(5);
let negated = -d; // -5秒

8. 与标准库互操作

rust 复制代码
use std::time::Duration as StdDuration;

// 从标准库转换
let std_duration = StdDuration::from_secs(5);
let time_duration = Duration::try_from(std_duration).unwrap();

// 转换为标准库(无符号)
let unsigned = time_duration.unsigned_abs();

// 与标准库比较
assert_eq!(Duration::seconds(5), StdDuration::from_secs(5));
assert!(Duration::seconds(10) > StdDuration::from_secs(5));

9. 格式化显示

rust 复制代码
let duration = Duration::hours(2) + Duration::minutes(30);

// 完整格式
println!("{}", duration); // "2h30m0s"

// 简洁格式(带精度)
println!("{:.2}", duration); // "2.50h"
println!("{:.0}", duration); // "3h"

10. 设计亮点

  1. 范围安全性 :使用 RangedI32 保证纳秒值始终有效
  2. 零成本抽象:编译时检查,运行时无额外开销
  3. 完备的数学运算:支持各种算术操作
  4. 良好的错误处理:提供 panic 和 Result 两种风格的 API
  5. 与标准库兼容:便于与现有代码集成

11. 性能优化

  • Niche Value Optimization :通过 Padding 字段优化内存布局
  • 内联函数 :大多数方法标记为 #[inline]
  • 常量求值:尽可能在编译时计算
  • 避免分支:使用位操作处理浮点数转换

12. 使用场景

  • 时间间隔计算:计算两个时间点之间的差值
  • 定时任务:设置延迟或周期性执行
  • 性能测量:测量代码执行时间
  • 时间运算:进行时间加减运算
  • 序列化/反序列化:作为时间数据的中间表示

这个实现特别适合需要处理相对时间、倒计时、时间差计算的场景,弥补了标准库 Duration 不支持负值的不足。

相关推荐
Chen--Xing5 小时前
LeetCode 49.字母异位词分组
c++·python·算法·leetcode·rust
古城小栈6 小时前
Go+Rust混合编程:高性能系统开发的最优解之一
golang·rust
云雾J视界10 小时前
告别手动寄存器编程:STM32-RS 生态如何重构嵌入式开发效率
rust·svd·嵌入式开发·寄存器·工具链·可编译·社区驱动
Source.Liu1 天前
【time-rs】月份枚举实现
rust·time
福大大架构师每日一题1 天前
2025年12月TIOBE编程语言排行榜,Go语言排名第15,Rust语言排名17。编程语言 R 重返前十。
开发语言·后端·rust
苏 凉1 天前
在 openEuler 24.03 LTS SP2 上安装部署 iSula 容器引擎及性能测试
开发语言·rust
ULTRA??1 天前
字符串处理小写字母转换大写字母
c++·python·rust
ZC·Shou2 天前
Rust 之二 各组件工具的源码、构建、配置、使用(二)
开发语言·ide·rust·工具·命令·clippy·rustfmt
ULTRA??2 天前
Rust的移动语义
c++·算法·rust