【问题标题】:How to measure execution time of a function?如何测量函数的执行时间?
【发布时间】:2021-10-20 03:52:57
【问题描述】:

我搜索了 SO 并找到了相关问题的答案,但我对三种不同的时钟定义感到困惑。考虑到我在 Windows 上使用 Mingw 进行编译;

  1. 不知道下面的代码是否可以? (我真的不需要纳秒或微秒的精度;只是测试......)
  2. 我应该使用哪一个?
  • std::chrono::high_resolution_clock
  • std::chrono::system_clock
  • std::chrono::steady_clock
#include <iostream>
#include <chrono>
...
...
...
void printTimeElapsed(
    std::chrono::high_resolution_clock::time_point t0,
    std::chrono::high_resolution_clock::time_point t1)
{
    int64_t hh; // hour
    int64_t mm; // min
    int64_t ss; // sec
    int64_t ml; // millisec
    int64_t mc; // microsec
    int64_t ns; // nanosec

    ns = std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count();
    std::cout << ns << std::endl;
    mc = ns / 1000;
    ns %= 1000;
    ml = mc / 1000;
    mc %= 1000;
    ss = ml / 1000;
    ml %= 1000;
    mm = ss / 60;
    ss %= 60;
    hh = mm / 60;
    mm %= 60;

    std::cout
        << std::setfill('0') << std::setw(3) << hh << ":"
        << std::setfill('0') << std::setw(2) << mm << ":"
        << std::setfill('0') << std::setw(2) << ss << "."
        << std::setfill('0') << std::setw(3) << ml << "."
        << std::setfill('0') << std::setw(3) << mc << "."
        << std::setfill('0') << std::setw(3) << ns << std::endl;
    return;
}
...
...
...
int main(
    int argc,
    char *argv[])
{
    std::chrono::high_resolution_clock::time_point t0;
    std::chrono::high_resolution_clock::time_point t1;
    ...
    ...
    t0 = std::chrono::high_resolution_clock::now();
    /* call the function to be measured */
    t1 = std::chrono::high_resolution_clock::now();
    printTimeElapsed(t0, t1);
    ...
    ...
    return (0);       
}

【问题讨论】:

标签: c++ time


【解决方案1】:

system_clock 不稳定稳定:受时间调整。 high_resolution_clock 不保证稳定

意味着用户使用steady_clock进行测量,因此实现者需要制作高分辨率的steady_clock

steady_clock 的 Windows 实现应基于QueryPerformanceCounter / QueryPerformanceFrequency,这是可用 API 的最高分辨率。对于 MSVC 是这样,需要检查 MinGW。

【讨论】:

    猜你喜欢
    • 2014-10-04
    • 2020-07-08
    • 2010-09-23
    • 2016-01-28
    • 2019-03-30
    • 2020-07-16
    • 1970-01-01
    • 2011-09-09
    相关资源
    最近更新 更多