我有一个函数运行了超过一百万次。我想通过打印 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/