c++ - 获取使用 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";
}
我找不到添加持续时间然后获得平均值的方法。
解决方案
如果你看一下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中看到它。
推荐阅读
- vba - VBA - 帮助调试出错的复制/粘贴
- ruby - Different Ways of Namespacing in Ruby
- javascript - 在没有 jquery 的 javascript 中添加和删除类
- html - 如何在标题中移动图像?
- java - 为什么JAVA 10中的var不能初始化为null?
- android - 从 ActivityB 我想将 ID 发送到 FragmentA 并更新 FramgentA 中的列表
- java - 一系列相关操作的设计模式
- c - 关于 Stream 和 getchar() 和 fgetc()
- go - 收听高级 Oracle 队列 (AQ)
- apache-spark - 在记录历史(聚合)火花流上运行 SQL 查询