C++ 標(biāo)準(zhǔn)庫 <chrono>的具體使用
下面對(duì) C++ 標(biāo)準(zhǔn)庫中 <chrono> 頭文件提供的高精度、類型安全的時(shí)間與時(shí)鐘工具做一次系統(tǒng)、深入的梳理,包括時(shí)鐘類別、duration 與 time_point 基礎(chǔ)、常用別名、運(yùn)算與轉(zhuǎn)換、定時(shí)與睡眠、格式化/解析,以及實(shí)踐建議。
一、概述
<chrono> 引入于 C++11,提供了類型安全的時(shí)間度量體系,替代了傳統(tǒng) C 風(fēng)格的
<ctime>。核心概念圍繞兩大模板類:
std::chrono::duration<Rep,Period>:表示一段時(shí)間長(zhǎng)度(例如 3.5 秒、100 毫秒)std::chrono::time_point<Clock,Duration>:表示某一時(shí)刻,相對(duì)于特定時(shí)鐘的紀(jì)元(epoch)
配合若干 時(shí)鐘(Clock) 類型,可進(jìn)行高精度測(cè)時(shí)、定時(shí)、時(shí)間點(diǎn)運(yùn)算、跨平臺(tái)的線程睡眠等。
二、時(shí)鐘(Clocks)
| 時(shí)鐘類型 | 說明 | 精度 | 單調(diào)性 |
|---|---|---|---|
| system_clock | 與系統(tǒng)實(shí)時(shí)時(shí)鐘對(duì)應(yīng),可轉(zhuǎn)換為日歷時(shí)間(time_t) | 操作系統(tǒng)定義 | 非單調(diào) |
| steady_clock | 單調(diào)、不可回?fù)?,適合測(cè)量間隔,不受系統(tǒng)時(shí)間調(diào)整影響 | 實(shí)現(xiàn)定義 | 單調(diào) |
| high_resolution_clock | 提供最高可用精度(通常是 steady_clock 或 system_clock) | 實(shí)現(xiàn)定義 | 取決于底層時(shí)鐘 |
using namespace std::chrono; auto t0 = steady_clock::now(); // …執(zhí)行某些耗時(shí)操作… auto t1 = steady_clock::now(); auto elapsed = t1 - t0; // 類型為 steady_clock::duration
三、duration:表示時(shí)間間隔
1. 定義
template<class Rep, class Period = std::ratio<1>> class duration;
Rep:底層數(shù)值類型(如 int64_t、double)
Period:刻度單位,以分?jǐn)?shù)形式表示:
- std::ratio<1,1000> → 毫秒
- std::ratio<60> → 分鐘
- std::nano/micro/milli/ratio<1>/kilo…
2. 常用別名
using nanoseconds = duration<long long, nano>; // 10?? s using microseconds = duration<long long, micro>; // 10?? s using milliseconds = duration<long long, milli>; // 10?3 s using seconds = duration<long long>; // 1 s using minutes = duration<long long, ratio<60>>; using hours = duration<long long, ratio<3600>>;
3. 運(yùn)算與轉(zhuǎn)換
- 加減乘除:對(duì)同種或可轉(zhuǎn)換 duration 之間可直接相加、相減;也可乘以/除以標(biāo)量。
- duration_cast<To>(d):將 d 強(qiáng)制轉(zhuǎn)換為 To,會(huì)截?cái)嗑榷撬纳嵛迦搿?/li>
- std::chrono::abs(d)(C++20)取絕對(duì)值。
auto d1 = 1500ms; // milliseconds auto d2 = 1s + 500ms; // 1500ms auto d3 = duration_cast<seconds>(d1); // 1s (截?cái)? auto d4 = d1 * 2; // 3000ms
四、time_point:表示時(shí)刻
1. 定義
template<class Clock, class Duration = Clock::duration> class time_point;
- Clock::duration:決定了 time_point 的底層精度
- 以時(shí)鐘的紀(jì)元(epoch)為參考,例如 system_clock 通常以 UNIX 紀(jì)元 (1970-01-01)
2. 構(gòu)造與置零
system_clock::time_point t0; // 默認(rèn)構(gòu)造:epoch auto t1 = system_clock::now(); // 當(dāng)前時(shí)刻
3. 運(yùn)算
- 加減 duration:tp + d 或 tp - d 得到新的 time_point
- 差值:t2 - t1 得到 duration
- 比較:支持 <,>,== 等
auto expire = t1 + 5min; // 5 分鐘后
if (system_clock::now() < expire) { … }
auto wait = expire - system_clock::now(); // duration
五、定時(shí)與線程睡眠
- std::this_thread::sleep_for(dur):阻塞當(dāng)前線程持續(xù)指定 duration
- std::this_thread::sleep_until(tp):阻塞至指定 time_point
#include <thread> std::cout << "Sleeping for 500ms...\n"; std::this_thread::sleep_for(500ms); std::cout << "Awake!\n";
- 精度取決于操作系統(tǒng)調(diào)度與底層時(shí)鐘,通常不保證毫秒級(jí)精確喚醒。
六、格式化與解析(C++20 起)
C++20 增加了 <chrono> 對(duì)日歷與格式化的支持,位于 <chrono> 或 <chrono> + <format>。
#include <chrono>
#include <format> // C++20
using namespace std::chrono;
auto now = system_clock::now();
auto dp = floor<days>(now);
year_month_day ymd = dp; // C++20 calendar 類型
auto time_str = std::format("{:%Y-%m-%d %H:%M:%S}", now);
// 例如 "2025-07-12 15:04:05"
- floor<Duration>(tp):向下取整至指定粒度
- year_month_day、weekday、month_day 等類型支持日歷運(yùn)算
- std::format 與 <format> 的時(shí)間格式 {:%Y-%m-%d} 與 strftime 類似,更類型安全。
七、實(shí)踐建議
測(cè)時(shí)請(qǐng)用 steady_clock
- 避免系統(tǒng)時(shí)間調(diào)整的影響;high_resolution_clock 也可,但需確認(rèn)其是否單調(diào)。
存儲(chǔ)/序列化用 system_clock
- 與現(xiàn)實(shí)世界時(shí)間對(duì)應(yīng),可轉(zhuǎn)換為/自 time_t,與外部系統(tǒng)交互友好。
慎用 duration_cast 截?cái)?/p>
- 若需四舍五入,手動(dòng)加半個(gè)單位再截?cái)?,或用浮點(diǎn) duration<double> 做中介。
避免睡眠“過度”依賴精度
- sleep_for 可能比請(qǐng)求時(shí)間更長(zhǎng);對(duì)高精度實(shí)時(shí)控制,應(yīng)配合忙等或操作系統(tǒng)定時(shí)器 API。
利用 C++20 日歷庫
- 對(duì)日期運(yùn)算(加月、驗(yàn)證閏年等)請(qǐng)使用 year_month_day 等類型,勝過手寫 tm 計(jì)算。
類型安全與可讀性
- 使用字面量(100ms, 2h)和 using namespace std::chrono_literals,代碼簡(jiǎn)潔且避免單位混淆。
通過以上對(duì) <chrono> 中時(shí)鐘、duration、time_point、定時(shí)、格式化與實(shí)踐建議的全面梳理,相信你能在性能測(cè)量、任務(wù)調(diào)度、日志時(shí)間戳與日歷運(yùn)算等場(chǎng)景中高效、正確地使用現(xiàn)代 C++ 時(shí)間庫。祝編碼順利!
到此這篇關(guān)于C++ 標(biāo)準(zhǔn)庫 <chrono>的具體使用的文章就介紹到這了,更多相關(guān)C++ <chrono>內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
QT網(wǎng)絡(luò)編程UDP下C/S架構(gòu)廣播通信(實(shí)例講解)
下面小編就為大家?guī)硪黄猀T網(wǎng)絡(luò)編程UDP下C/S架構(gòu)廣播通信(實(shí)例講解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-07-07
Qt如何實(shí)現(xiàn)文本編輯器光標(biāo)高亮技術(shù)
這篇文章主要為大家詳細(xì)介紹了Qt如何實(shí)現(xiàn)文本編輯器光標(biāo)高亮技術(shù),文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,有需要的小伙伴可以了解下2025-06-06
詳解C++中十六進(jìn)制字符串轉(zhuǎn)數(shù)字(數(shù)值)
這篇文章主要介紹了詳解C++中十六進(jìn)制字符串轉(zhuǎn)數(shù)字(數(shù)值)的相關(guān)資料,這里提供兩種實(shí)現(xiàn)方法,需要的朋友可以參考下2017-08-08
C語言學(xué)生成績(jī)管理系統(tǒng)課程設(shè)計(jì)
這篇文章主要為大家詳細(xì)介紹了C語言學(xué)生成績(jī)管理系統(tǒng)課程設(shè)計(jì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01
C++實(shí)現(xiàn)線程同步的四種方式總結(jié)
這篇文章主要為大家詳細(xì)介紹了C++實(shí)現(xiàn)線程同步的四種方式,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)C++有一定的幫助,需要的可以參考一下2022-11-11

