C++記錄程序運行時間的四種方法
1. 使用 <chrono> 庫(C++11及以后版本)
<chrono>
庫提供了高精度的時間測量功能。
#include <iostream> #include <chrono> int main() { auto start = std::chrono::high_resolution_clock::now(); // Your code here // ... auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start).count(); std::cout << "Elapsed time: " << duration << " ms\n"; return 0; }
2. 使用 <ctime> 庫(較舊但常用的方法)
<ctime>
庫提供了基于系統(tǒng)時間的函數(shù)clock()。
#include <iostream> #include <ctime> int main() { clock_t start = clock(); //也可以double start = clock(); // Your code here // ... clock_t end = clock(); double cpu_time_used = static_cast<double>(end - start) / CLOCKS_PER_SEC; // /CLOCKS_PER_SEC將結(jié)果轉(zhuǎn)為以秒為單位 std::cout << "CPU time used: " << cpu_time_used << " s\n"; return 0; }
3、使用第三方庫(如Boost.Timer)
Boost庫提供了一個計時器模塊,用于測量代碼塊的執(zhí)行時間。
首先,你需要安裝 Boost庫,并在項目中包含Boost.Timer頭文件。
#include <boost/timer/timer.hpp> #include <iostream> int main() { boost::timer::auto_cpu_timer t; // 自動測量和打印執(zhí)行時間 // Your code here // ... return 0; }
4. 使用Windows API函數(shù)(Windows平臺特有)
4.1 使用 GetTickCount()
這個函數(shù)返回從系統(tǒng)啟動開始經(jīng)過的毫秒數(shù)。GetTickCount()
的精度在1到15毫秒之間,并且其值會在大約49.7天后回繞。
#include <windows.h> #include <iostream> int main() { DWORD start = GetTickCount(); // ... 執(zhí)行你的代碼 ... DWORD end = GetTickCount(); std::cout << "程序運行時間: " << (end - start) << " 毫秒" << std::endl; return 0; }
4.2 使用 QueryPerformanceCounter() 和 QueryPerformanceFrequency()
這兩個函數(shù)提供了更高的精度,通常在微秒級別。
#include <windows.h> #include <iostream> int main() { LARGE_INTEGER start, end, freq; QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&start); // ... 執(zhí)行你的代碼 ... QueryPerformanceCounter(&end); double elapsedTime = (double)(end.QuadPart - start.QuadPart) / freq.QuadPart * 1000.0; // 毫秒 std::cout << "程序運行時間: " << elapsedTime << " 毫秒" << std::endl; return 0; }
到此這篇關(guān)于C++記錄程序運行時間的四種方法的文章就介紹到這了,更多相關(guān)C++程序運行時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Linux C/C++實現(xiàn)DNS客戶端請求域名IP的示例代碼
DNS全稱:Domain Name System,域名解析系統(tǒng),是互聯(lián)網(wǎng)的一項服務(wù),本文主要介紹了C/C++如何實現(xiàn)DNS客戶端請求域名IP,感興趣的可以了解下2024-03-03VSCode插件開發(fā)全攻略之打包、發(fā)布、升級的詳細(xì)教程
這篇文章主要介紹了VSCode插件開發(fā)全攻略之打包、發(fā)布、升級的教程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-05-05C語言關(guān)鍵字const和指針的結(jié)合使用
這篇文章主要介紹了C語言關(guān)鍵字const和指針的結(jié)合,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02