C++ chrono与时间编程全攻略:从std::chrono到C++20日历
本文系统讲解C++时间编程的方方面面,从基础chrono库到C++20日历与时间区扩展,配合大量实战代码和性能测试数据,助你彻底掌握C++时间编程。
一、chrono库基础
1.1 三大核心概念
C++11引入的<chrono>库基于三个核心概念:
#include <chrono>
#include <iostream>
int main() {
// 1. duration:时间间隔
std::chrono::seconds sec(5);
std::chrono::milliseconds ms(500);
std::chrono::duration<double, std::ratio<1>> five_sec(5.0);
// 2. time_point:时间点
auto now = std::chrono::steady_clock::now();
std::cout << "ticks: " << now.time_since_epoch().count() << std::endl;
// 3. clock:时钟
// steady_clock: 单调递增,适合计时
// system_clock: 系统时间,可调整
// high_resolution_clock: 最高精度
return 0;
}
1.2 duration详解
#include <chrono>
#include <iostream>
#include <ratio>
int main() {
// 预定义duration类型
std::chrono::hours h(1);
std::chrono::minutes m(90);
std::chrono::seconds s(3600);
std::chrono::milliseconds ms(1000);
std::chrono::microseconds us(1000);
std::chrono::nanoseconds ns(1000);
// 自动转换(小单位到大单位会截断)
std::chrono::seconds s2 = std::chrono::milliseconds(2500);
std::cout << s2.count() << " seconds" << std::endl; // 2 seconds
// 精确转换
auto result = std::chrono::duration_cast<std::chrono::milliseconds>(s2);
std::cout << result.count() << " ms" << std::endl; // 2000 ms
// 自定义duration
using half_seconds = std::chrono::duration<int, std::ratio<1, 2>>;
half_seconds hs(10); // 10 * 0.5 = 5 seconds
auto conv = std::chrono::duration_cast<std::chrono::seconds>(hs);
std::cout << conv.count() << " seconds" << std::endl; // 5 seconds
// 算术运算
auto total = h + m + s;
std::cout << std::chrono::duration_cast<std::chrono::seconds>(total).count()
<< " seconds" << std::endl; // 5400 seconds
return 0;
}
1.3 三种时钟对比
| 时钟类型 | 特点 | 用途 |
|---|---|---|
steady_clock |
单调递增,不可调整 | 性能计时、超时检测 |
system_clock |
系统实时时钟,可被修改 | 日志时间戳、显示时间 |
high_resolution_clock |
平台最高精度 | 高精度性能测试 |
#include <chrono>
#include <iostream>
int main() {
// steady_clock:推荐用于性能测试
auto start = std::chrono::steady_clock::now();
// ... 被测代码 ...
volatile int sum = 0;
for (int i = 0; i < 1000000; ++i) sum += i;
auto end = std::chrono::steady_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end - start
1742



被折叠的 条评论
为什么被折叠?



