c++如何测量代码的执行时间_C++计算函数运行时长的几种方式

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

在C++开发中,测量代码或函数的执行时间对性能分析和优化非常重要。以下是几种常用且有效的方法来精确计算函数运行时长。

使用 chrono 高精度时钟(推荐)

C++11 引入了 chrono 库,提供了高精度、跨平台的时间测量功能,是目前最推荐的方式。

你可以使用 std::chrono::high_resolution_clocksteady_clock 来记录时间点,然后计算差值。

示例代码:

#include 
#include 

void someFunction() { // 模拟耗时操作 for (int i = 0; i < 1000000; ++i); }

int main() { auto start = std::chrono::high_resolution_clock::now();

someFunction();

auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast(end - start);

std::cout << "函数执行时间:" << duration.count() << " 微秒\n";
return 0;

}

可以根据需要将单位改为 millisecondsnanoseconds 等。

使用 clock() 函数(传统方式)

来自 clock() 是较老但广泛支持的方法,它返回程序运行的“时钟滴答”数。

通过除以 CLOCKS_PER_SEC 转换为秒。

示例代码:

#include 
#include 

int main() { clock_t start = clock();

// 执行目标函数
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 
#include 

class Timer { public: Timer() { start = std::chrono::high_resolution_clock::now(); }

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(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./link/706e79e774e8345ecccc7ed401793d9e

基本上就这些。日常开发中用 chrono 就足够了,简单、精准、可读性强。