c++ - 获取使用 std::chrono 花费的平均时间

标签 c++ average duration c++-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";
}

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

最佳答案

如果你看 std::chrono::duration<Rep,Period>::count , 你可以看到你可以使用

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

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

The number of ticks for this duration.

完整:

#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 .

关于c++ - 获取使用 std::chrono 花费的平均时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57995392/

相关文章:

python - 计算混合文本文件中特定数字的平均值?

c# - 为什么 TimeSpan.Duration() 是方法而不是属性?

php - Gettext 缓存的烦恼

youtube-api - Youtube API v3 持续时间播放列表项

c++ - 有效地获取给定数字的所有除数

c++ - PPL critical_section/parallel_for 在 Visual Studio 2010 下崩溃?

c++ - 使用计算着色器处理渲染目标

c++ - 如何检查文件是否复制成功? (可移植解决方案)C++

Javascript 平均计算器(用户输入的多个值)

减少信号数据噪声的算法?