C++中推荐使用chrono库测量函数执行时间,示例代码展示如何用high_resolution_clock获取微秒级精度,也可封装Timer类便于复用,传统clock()方法因依赖CPU时间而精度较低,专业场景可用Google Benchmark。

在C++开发中,测量代码或函数的执行时间对性能分析和优化非常重要。以下是几种常用且有效的方法来精确计算函数运行时长。
使用 chrono 高精度时钟(推荐)
C++11 引入了 chrono 库,提供了高精度、跨平台的时间测量功能,是目前最推荐的方式。你可以使用 std::chrono::high_resolution_clock 或 steady_clock 来记录时间点,然后计算差值。
示例代码:
#include <iostream>
#include <chrono>
<p>void someFunction() {
// 模拟耗时操作
for (int i = 0; i < 1000000; ++i);
}</p><p>int main() {
auto start = std::chrono::high_resolution_clock::now();</p><pre class="brush:php;toolbar:false;">someFunction();
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);
std::cout << "函数执行时间:" << duration.count() << " 微秒\n";
return 0;}
可以根据需要将单位改为 milliseconds、nanoseconds 等。
立即学习“C++免费学习笔记(深入)”;
使用 clock() 函数(传统方式)
来自通过除以 CLOCKS_PER_SEC 转换为秒。
示例代码:
#include <iostream>
#include <ctime>
<p>int main() {
clock_t start = clock();</p><pre class="brush:php;toolbar:false;">// 执行目标函数
for (int i = 0; i < 1000000; ++i);
clock_t end = clock();
double elapsed = double(end - start) / CLOCKS_PER_SEC;
std::cout << "执行时间:" << elapsed << " 秒\n";
return 0;}
注意:clock() 测量的是CPU时间,在多线程或系统空闲时可能不够准确。
封装成计时类便于复用
为了方便多次测量,可以封装一个简单的计时类。示例:
#include <iostream>
#include <chrono>
<p>class Timer {
public:
Timer() { start = std::chrono::high_resolution_clock::now(); }</p><pre class="brush:php;toolbar:false;">void reset() { start = std::chrono::high_resolution_clock::now(); }
long long elapsed_microseconds() const {
auto now = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::microseconds>(now - start).count();
}
long long elapsed_milliseconds() const {
return elapsed_microseconds() / 1000;
}private: std::chrono::high_resolution_clock::time_point start; };
// 使用示例 int main() { Timer timer; for (int i = 0; i
这种方式适合在多个地方重复使用,提升代码整洁度。
使用第三方库(如 Google Benchmark)
对于更专业的性能测试,可以使用 Google Benchmark 库,它能自动处理多次运行、统计平均值、标准差等。虽然配置稍复杂,但在做性能对比或微基准测试时非常强大。
GitHub 地址:https://www.php.cn/link/706e79e774e8345ecccc7ed401793d9e
基本上就这些。日常开发中用 chrono 就足够了,简单、精准、可读性强。











