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> 库提供了基于系统时间的函数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将结果转为以秒为单位
std::cout << "cpu time used: " << cpu_time_used << " s\n";
return 0;
}3、使用第三方库(如boost.timer)
boost库提供了一个计时器模块,用于测量代码块的执行时间。
首先,你需要安装 boost库,并在项目中包含boost.timer头文件。
#include <boost/timer/timer.hpp>
#include <iostream>
int main() {
boost::timer::auto_cpu_timer t; // 自动测量和打印执行时间
// your code here
// ...
return 0;
}4. 使用windows api函数(windows平台特有)
4.1 使用 gettickcount()
这个函数返回从系统启动开始经过的毫秒数。gettickcount() 的精度在1到15毫秒之间,并且其值会在大约49.7天后回绕。
#include <windows.h>
#include <iostream>
int main() {
dword start = gettickcount();
// ... 执行你的代码 ...
dword end = gettickcount();
std::cout << "程序运行时间: " << (end - start) << " 毫秒" << std::endl;
return 0;
}4.2 使用 queryperformancecounter() 和 queryperformancefrequency()
这两个函数提供了更高的精度,通常在微秒级别。
#include <windows.h>
#include <iostream>
int main() {
large_integer start, end, freq;
queryperformancefrequency(&freq);
queryperformancecounter(&start);
// ... 执行你的代码 ...
queryperformancecounter(&end);
double elapsedtime = (double)(end.quadpart - start.quadpart) / freq.quadpart * 1000.0; // 毫秒
std::cout << "程序运行时间: " << elapsedtime << " 毫秒" << std::endl;
return 0;
}到此这篇关于c++记录程序运行时间的四种方法的文章就介绍到这了,更多相关c++程序运行时间内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论