以C++为单位测量程序的 CPU 时间和挂钟时间

Measure CPU time and wall clock time of a program in C++

本文关键字:时间 钟时间 CPU 为单位 C++ 测量 程序      更新时间:2023-10-16

std::clock()测量程序持续时间内的时钟周期数。在下面的代码中,它是计算 CPU 时间还是挂钟时间?

标准::clock_t开始; 双倍持续时间;

start = std::clock();
/* Your algorithm here */
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;

在另一种情况下,使用以下代码:

std::clock_t start;
double time;
start = std::clock();
time = start  / (double) CLOCKS_PER_SEC;

时间的价值是什么?

从文档中:

std::clock时间可能比挂钟更快或更慢,具体取决于操作系统提供给程序的执行资源。

在这种情况下,您还可以编写一个简单的lambda(在C++14中特别简单),用于测量任何可调用对象所花费的时间,如下所示:

#include <iostream>
#include <chrono>
auto timing = [](auto&& F, auto&&... params) // need C++14 for auto lambda parameters
{
    auto start = std::chrono::steady_clock::now();
    F(std::forward<decltype(params)>(params)...); // execute the function 
    return std::chrono::duration_cast<std::chrono::milliseconds>(
               std::chrono::steady_clock::now() - start).count();
};
void f(std::size_t numsteps) // we'll measure how long this function runs
{
    volatile std::size_t i{}; // need volatile, otherwise the compiler optimizes the loop
    for(i = 0; i < numsteps; ++i);
}
int main()
{
    auto taken = timing(f, 500'000'000); // measure the time taken to run f()
    std::cout << "Took " << taken << " milliseconds" << std::endl;
    taken = timing(f, 100'000'000); // measure again
    std::cout << "Took " << taken << " milliseconds" << std::endl;
}

然后,您可以随时重用 lambda,以便对某些内容进行计时。