【问题标题】:Measure CPU time and wall clock time of a program in C++在 C++ 中测量程序的 CPU 时间和挂钟时间
【发布时间】:2023-03-03 00:28:02
【问题描述】:

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

std::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;

时间的价值是什么?

【问题讨论】:

标签: c++


【解决方案1】:

在这种情况下,您还可以编写一个简单的 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。

【讨论】:

    【解决方案2】:

    来自the documentation

    std::clock 时间可能会比挂钟快或慢,这取决于操作系统给予程序的执行资源。

    【讨论】:

    • 那么,用 C++ 记录挂钟时间的好方法是什么?
    • @firefly 使用类似std::chrono::time_point 的东西。 (C++11)
    • 我分享的链接中的示例也获得了挂钟时间。
    猜你喜欢
    • 2013-07-04
    • 1970-01-01
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 2019-11-02
    • 1970-01-01
    • 2013-12-25
    相关资源
    最近更新 更多