首页 > 解决方案 > 获取使用 std::chrono 的平均时间

问题描述

我有一个运行超过一百万次的函数。我想通过打印对函数的 10,000 次调用的持续时间总和来打印函数运行所需的持续时间。

在每个函数的开头,我都有这样的东西:

int counter = 0;
auto duration_total = 0; //not sure about the type
std::chrono::high_resolution_clock::time_point t1, t2, duration;

t1 = std::chrono::high_resolution_clock::now(); 
Function f(){
  counter++;
}

t2 = std::chrono::high_resolution_clock::now();
duration= std::chrono::duration_cast<std::chrono::nanoseconds>( t2 - t1 ).count();
duration_total += duration;

if(counter %10000 == 0){
      long int average_duration = duration_total/10000;
      duration_total = 0;
      cout << average_duration << "\n";
}

我找不到添加持续时间然后获得平均值的方法。

标签: c++averagedurationchrono

解决方案


如果你看一下std::chrono::duration<Rep,Period>::count,你会发现你可以使用

int duration = std::chrono::duration_cast<std::chrono::nanoseconds>( t2 - t1 ).count();

(或其他东西,例如,unsigned long),因为返回值是

此持续时间的刻度数。

在全:

#include <iostream>
#include <chrono>

int main()
{
    int counter = 0;
    auto duration_total = 0; //not sure about the type
    std::chrono::high_resolution_clock::time_point t1, t2;

    t1 = std::chrono::high_resolution_clock::now(); 

    t2 = std::chrono::high_resolution_clock::now();
    int duration = std::chrono::duration_cast<std::chrono::nanoseconds>( t2 - t1 ).count();
    duration_total += duration;

    if(counter %10000 == 0){
          long int average_duration = duration_total/10000;
          duration_total = 0;
          std::cout << average_duration << "\n";
    }
}

在Coliru中看到它。


推荐阅读