在C++中准确测量代码执行时间可以使用<chrono>
头文件中的函数。以下是一个简单的示例:
#include <iostream>
#include <chrono>
int main() {
// 获取当前时间点
auto start = std::chrono::high_resolution_clock::now();
// 执行需要测量时间的代码
for (int i = 0; i < 1000000; ++i) {
// do something
}
// 获取结束时间点
auto end = std::chrono::high_resolution_clock::now();
// 计算时间差
std::chrono::duration<double> duration = end - start;
// 输出执行时间
std::cout << "Execution time: " << duration.count() << " seconds" << std::endl;
return 0;
}
在这个示例中,首先使用std::chrono::high_resolution_clock::now()
获取当前时间点,然后执行需要测量时间的代码,再次获取结束时间点,并计算时间差。最后输出执行时间。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:C++程序执行时间如何测量