【问题标题】:Why does the runtime of high_resolution_clock increase with the greater frequency I call it?为什么 high_resolution_clock 的运行时间会随着我调用它的频率越高而增加?
【发布时间】:2023-01-24 03:55:51
【问题描述】:

在下面的代码中,我重复两次调用std::chrono::high_resolution_clock::now,并测量这两次调用之间花费的时间。我预计这次会非常小,因为在这两个调用之间没有运行其他代码。但是,我观察到奇怪的行为。

正如预期的那样,对于小 N,最大元素在几纳秒内。然而,我增加 N 的次数越多,我就会得到非常大的异常值,并且已经达到几毫秒。为什么会这样?

换句话说,为什么在下面的代码中,当我增加 N 时,v 的最大元素会增加?

#include <iostream>
#include <vector>
#include <chrono>
#include <algorithm>

int main()
{
    using ns = std::chrono::nanoseconds;
    
    uint64_t N = 10000000;
    std::vector<uint64_t> v(N, 0);
    for (uint64_t i = 0; i < N; i++) {
        auto start = std::chrono::high_resolution_clock::now();
        v[i] = std::chrono::duration_cast<ns>(std::chrono::high_resolution_clock::now() - start).count();
    }
    
    std::cout << "max: " << *std::max_element(v.begin(), v.end()) << std::endl;
    
    return 0;
}

【问题讨论】:

  • 您的机器中发生了其他事情,这些事情可能比您的程序具有更高的优先级。例如,在我的机器上有 1500 个线程在运行,我只是浏览这个。程序运行的时间越长,发生某些事情的可能性就越高。
  • 一种可能性是,当您增加运行时长度时,您会增加进程暂停的机会,以便操作系统可以执行其他一些工作。 FWIW 如果你想对一些代码进行基准测试,你真的会想要使用像谷歌基准测试这样的专用工具。基准测试很难做到正确,因为今天的编译器可以优化很多东西。
  • 旁注:不要与high_resolution_clock 打交道。它重视分辨率高于稳定性,并可能使用后备时钟来做愚蠢的事情,比如及时倒退。创建它的人之一recommends never using high_resolution_clock at all

标签: c++ system-calls c++-chrono


【解决方案1】:

您运行循环的时间越长,您的操作系统就越有可能确定您的线程目前已经消耗了足够的资源并将其挂起。循环运行的时间越长,发生这种暂停的可能性就越大之间那些电话。

由于您只查看“最大”时间,因此只需发生一次即可使最大时间达到毫秒范围。

【讨论】:

    猜你喜欢
    • 2021-11-22
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2014-03-01
    相关资源
    最近更新 更多