C++記錄程序運(yùn)行時(shí)間的四種方法
1. 使用 <chrono> 庫(C++11及以后版本)
<chrono> 庫提供了高精度的時(shí)間測(cè)量功能。
#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í)間的函數(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庫提供了一個(gè)計(jì)時(shí)器模塊,用于測(cè)量代碼塊的執(zhí)行時(shí)間。
首先,你需要安裝 Boost庫,并在項(xiàng)目中包含Boost.Timer頭文件。
#include <boost/timer/timer.hpp>
#include <iostream>
int main() {
boost::timer::auto_cpu_timer t; // 自動(dòng)測(cè)量和打印執(zhí)行時(shí)間
// Your code here
// ...
return 0;
}4. 使用Windows API函數(shù)(Windows平臺(tái)特有)
4.1 使用 GetTickCount()
這個(gè)函數(shù)返回從系統(tǒng)啟動(dòng)開始經(jīng)過的毫秒數(shù)。GetTickCount() 的精度在1到15毫秒之間,并且其值會(huì)在大約49.7天后回繞。
#include <windows.h>
#include <iostream>
int main() {
DWORD start = GetTickCount();
// ... 執(zhí)行你的代碼 ...
DWORD end = GetTickCount();
std::cout << "程序運(yùn)行時(shí)間: " << (end - start) << " 毫秒" << std::endl;
return 0;
}4.2 使用 QueryPerformanceCounter() 和 QueryPerformanceFrequency()
這兩個(gè)函數(shù)提供了更高的精度,通常在微秒級(jí)別。
#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 << "程序運(yùn)行時(shí)間: " << elapsedTime << " 毫秒" << std::endl;
return 0;
}到此這篇關(guān)于C++記錄程序運(yùn)行時(shí)間的四種方法的文章就介紹到這了,更多相關(guān)C++程序運(yùn)行時(shí)間內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C語言的進(jìn)制轉(zhuǎn)換及算法實(shí)現(xiàn)教程
這篇文章主要介紹了C語言的進(jìn)制轉(zhuǎn)換及算法實(shí)現(xiàn)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
VS2022實(shí)現(xiàn)VC++打包生成安裝文件圖文詳細(xì)歷程
本文主要介紹了VS2022實(shí)現(xiàn)VC++打包生成安裝文件圖文詳細(xì)歷程,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-02-02
C++中的opeartor?new和placement?new使用步驟
這篇文章主要介紹了C++中的opeartor?new和placement?new詳解,在很多情況下,placement?new的使用方法和其他普通的new有所不同。這里提供了它的使用步驟,需要的朋友可以參考下2022-10-10
FFmpeg實(shí)戰(zhàn)之利用ffplay實(shí)現(xiàn)自定義輸入流播放
ffplay是FFmpeg提供的一個(gè)極為簡(jiǎn)單的音視頻媒體播放器,可以用于音視頻播放、可視化分析。本文將利用ffplay實(shí)現(xiàn)自定義輸入流播放,需要的可以參考一下2022-12-12
C語言求Fibonacci斐波那契數(shù)列通項(xiàng)問題的解法總結(jié)
斐波那契數(shù)列相關(guān)問題是考研和ACM中常見的算法題目,這里特地為大家整理了C語言求Fibonacci斐波那契數(shù)列通項(xiàng)問題的解法總結(jié),需要的朋友可以參考下2016-06-06

