使用chrono模块可精确测量函数运行时间,通过记录调用前后的时间点并计算差值实现。包含头文件<chrono>后,用high_resolution_clock::now()获取起始和结束时间,再用duration_cast转换为所需单位如微秒、毫秒等,示例代码展示了对一个循环函数的计时;还可封装为宏TIMEIT,简化重复计时操作,该方法自C++11起推荐使用,精度高且跨平台可靠。

在C++中,计算一个函数运行时间的常用方法是使用标准库中的 chrono 模块。它提供了高精度的时间测量功能,适合用于性能测试和函数耗时分析。
使用 chrono 计算函数运行时间
通过记录函数调用前后的时刻,相减即可得到执行时间。以下是基本步骤:
- 包含头文件:#include <chrono>
- 在函数调用前获取起始时间
- 在函数调用后获取结束时间
- 计算时间差并输出
示例代码:
#include <iostream>
#include <chrono>
<p>void testFunction() {
// 模拟耗时操作
for (int i = 0; i < 1000000; ++i) {
// 做一些计算
volatile int x = i * i;
}
}</p><p>int main() {
// 记录开始时间
auto start = std::chrono::high_resolution_clock::now();</p><pre class='brush:php;toolbar:false;'>// 调用目标函数
testFunction();
// 记录结束时间
auto end = std::chrono::high_resolution_clock::now();
// 计算耗时(微秒)
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << "函数执行时间:" << duration.count() << " 微秒" << std::endl;
return 0;}
立即学习“C++免费学习笔记(深入)”;
支持多种时间单位
可以根据需要将时间差转换为不同单位:
- 纳秒:std::chrono::nanoseconds
- 微秒:std::chrono::microseconds
- 毫秒:std::chrono::milliseconds
- 秒:std::chrono::seconds
例如,要以毫秒显示:
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); std::cout << "耗时:" << duration.count() << " 毫秒";
封装成通用计时函数
可以写一个简单的宏或模板函数来简化重复代码:
#define TIMEIT(func) { \
auto t1 = std::chrono::high_resolution_clock::now(); \
func; \
auto t2 = std::chrono::high_resolution_clock::now(); \
auto ms = std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1).count(); \
std::cout << "函数耗时 " << ms << " 微秒\n"; \
}
使用方式:
TIMEIT(testFunction());
基本上就这些。chrono 是 C++11 起推荐的方式,精度高、跨平台,比传统的 clock() 更可靠。











