目錄
Getting the current time
Measuring execution time accurately
Working with time points and durations
Formatting and parsing time (C 20 )
首頁 後端開發 C++ 在C中使用std :: Chrono

在C中使用std :: Chrono

Jul 15, 2025 am 01:30 AM
php java 程式設計

std::chrono在C 中用於處理時間,包括獲取當前時間、測量執行時間、操作時間點與持續時間及格式化解析時間。 1. 獲取當前時間使用std::chrono::system_clock::now(),可轉換為可讀字符串但係統時鐘可能不單調;2. 測量執行時間應使用std::chrono::steady_clock以確保單調性,並通過duration_cast轉換為毫秒、秒等單位;3. 時間點(time_point)和持續時間(duration)可相互操作,但需注意單位兼容性和時鐘紀元(epoch)差異;4. C 20支持時間格式化與解析,需使用std::format和std::parse,依賴編譯器對C 20的支持。

Using std::chrono in C

Using std::chrono in C can be really useful once you get the hang of it. It's part of the standard library and gives you solid tools for handling time — whether that's measuring durations, working with timestamps, or dealing with time zones in C 20 and beyond.

Using std::chrono in C

Getting the current time

To grab the current point in time, you usually go with std::chrono::system_clock::now() . That gives you a time_point representing right now.

 auto now = std::chrono::system_clock::now();

This is often used when you want to measure how long something takes or just log a timestamp. If you need to convert it to something readable like a string, you'll typically convert it to time_t and use ctime or similar:

Using std::chrono in C
 std::time_t now_c = std::chrono::system_clock::to_time_t(now);
std::cout << "Current time: " << std::ctime(&now_c);

Keep in mind that system_clock might not be monotonic — if someone changes the system time, it could jump forward or backward. For timing purposes, read on.


Measuring execution time accurately

When you want to measure how long a piece of code runs, steady_clock is your friend. It's monotonic (won't go backwards), which makes it safe for timing.

Using std::chrono in C

Here's a common pattern:

 auto start = std::chrono::steady_clock::now();

// ... do some work ...

auto end = std::chrono::steady_clock::now();
auto duration = end - start;

If you want to show this in milliseconds or seconds, you'll cast it using duration_cast :

 auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
std::cout << "Took " << ms << " ms\n";

You can also use microseconds , nanoseconds , or even seconds . Just keep in mind that converting from higher precision (like nanoseconds) to lower (like seconds) will truncate unless you cast properly.


Working with time points and durations

  • A time_point is a specific moment.
  • A duration is a span of time (like 5 seconds).

They're separate types, but they work together. You can add a duration to a time_point to get a new time_point:

 auto then = now std::chrono::hours(2);

This is handy when scheduling events or waiting until a certain time. Just make sure both sides of the operation are using compatible units — mixing hours and milliseconds won't cause errors, but it might not do what you expect unless you explicitly convert.

Also, don't assume that all clocks start at zero — their epoch (starting point) varies:

  • system_clock typically starts in 1970 (like Unix time).
  • steady_clock has an arbitrary epoch, so comparing its time_points across runs doesn't make sense.

Formatting and parsing time (C 20 )

With C 20, <chrono> got better support for formatting dates and times directly:

 auto now = std::chrono::system_clock::now();
std::cout << "Formatted: " << std::format("{:%Y-%m-%d %H:%M}", now) << "\n";

Parsing time strings also became possible:

 std::istringstream ss("2024-03-15 12:30");
std::chrono::system_clock::time_point tp;
ss >> std::parse("%Y-%m-%d %H:%M", tp);

This is super helpful when reading logs or config files with timestamps. But remember, these features require C 20 and good compiler support (like GCC 13 , Clang 15 , or MSVC with latest STL).


So yeah, std::chrono is pretty powerful once you understand the basic types and when to use each clock. Not too hard, just a bit easy to mix up at first.

以上是在C中使用std :: Chrono的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

在PHP中評論代碼 在PHP中評論代碼 Jul 18, 2025 am 04:57 AM

PHP註釋代碼常用方法有三種:1.單行註釋用//或#屏蔽一行代碼,推薦使用//;2.多行註釋用/.../包裹代碼塊,不可嵌套但可跨行;3.組合技巧註釋如用/if(){}/控制邏輯塊,或配合編輯器快捷鍵提升效率,使用時需注意閉合符號和避免嵌套。

撰寫PHP評論的提示 撰寫PHP評論的提示 Jul 18, 2025 am 04:51 AM

寫好PHP註釋的關鍵在於明確目的與規範,註釋應解釋“為什麼”而非“做了什麼”,避免冗餘或過於簡單。 1.使用統一格式,如docblock(/*/)用於類、方法說明,提升可讀性與工具兼容性;2.強調邏輯背後的原因,如說明為何需手動輸出JS跳轉;3.在復雜代碼前添加總覽性說明,分步驟描述流程,幫助理解整體思路;4.合理使用TODO和FIXME標記待辦事項與問題,便於後續追踪與協作。好的註釋能降低溝通成本,提升代碼維護效率。

通過評論提高可讀性 通過評論提高可讀性 Jul 18, 2025 am 04:46 AM

寫好註釋的關鍵在於說明“為什麼”而非僅“做了什麼”,提升代碼可讀性。 1.註釋應解釋邏輯原因,例如值選擇或處理方式背後的考量;2.對複雜邏輯使用段落式註釋,概括函數或算法的整體思路;3.定期維護註釋確保與代碼一致,避免誤導,必要時刪除過時內容;4.在審查代碼時同步檢查註釋,並通過文檔記錄公共邏輯以減少代碼註釋負擔。

編寫有效的PHP評論 編寫有效的PHP評論 Jul 18, 2025 am 04:44 AM

註釋不能馬虎是因為它要解釋代碼存在的原因而非功能,例如兼容老接口或第三方限制,否則看代碼的人只能靠猜。必須加註釋的地方包括複雜的條件判斷、特殊的錯誤處理邏輯、臨時繞過的限制。寫註釋更實用的方法是根據場景選擇單行註釋或塊註釋,函數、類、文件開頭用文檔塊註釋說明參數與返回值,並保持註釋更新,對複雜邏輯可在前面加一行概括整體意圖,同時不要用註釋封存代碼而應使用版本控制工具。

快速PHP安裝教程 快速PHP安裝教程 Jul 18, 2025 am 04:52 AM

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

學習PHP:初學者指南 學習PHP:初學者指南 Jul 18, 2025 am 04:54 AM

易於效率,啟動啟動tingupalocalserverenverenvirestoolslikexamppandacodeeditorlikevscode.1)installxamppforapache,mysql,andphp.2)uscodeeditorforsyntaxssupport.3)

PHP開發環境設置 PHP開發環境設置 Jul 18, 2025 am 04:55 AM

第一步選擇集成環境包XAMPP或MAMP搭建本地服務器;第二步根據項目需求選擇合適的PHP版本並配置多版本切換;第三步選用VSCode或PhpStorm作為編輯器並搭配Xdebug進行調試;此外還需安裝Composer、PHP_CodeSniffer、PHPUnit等工具輔助開發。

PHP評論語法 PHP評論語法 Jul 18, 2025 am 04:56 AM

PHP註釋有三種常用方式:單行註釋適合簡要說明代碼邏輯,如//或#用於當前行解釋;多行註釋/*...*/適合詳細描述函數或類的作用;文檔註釋DocBlock以/**開頭,為IDE提供提示信息。使用時應避免廢話、保持同步更新,並勿長期用註釋屏蔽代碼。

See all articles