[英]Get average of time spent using 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";
}
我找不到增加持续时间然后求平均值的方法。
您在启动时创建一个时钟,在停止时创建一个时钟。 从另一个时钟中减去一个时钟时,您会得到一个持续时间。 将持续时间除以迭代次数。
例:
#include <chrono>
#include <functional>
#include <iostream>
template<typename T>
auto timeit(size_t iterations, std::function<void()> func_to_test) {
auto start = std::chrono::high_resolution_clock::now();
for(size_t i = 0; i < iterations; ++i)
func_to_test();
auto end = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<T>(end - start) / iterations;
}
int main() {
auto dur =
timeit<std::chrono::microseconds>(10000, [] { system("echo Hello World"); });
std::cout << dur.count() << " µs\n";
}
如果需要汇总各个运行,请保留要添加到的工期变量。 我正在重用相同的timeit
函数,但如果只想运行一次,则可以删除其中的iteration
内容。
int main() {
std::chrono::microseconds tot{0};
size_t iterations = 0;
for(size_t i = 0; i < 10; ++i) {
// sum up the total time spent
tot += timeit<decltype(tot)>(1, [] { system("echo Hello World"); });
++iterations;
}
// divide with the number of iterations
std::cout << (tot / iterations).count() << " µs\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中看到它。
首先,这里的类型是int:
auto duration_total = 0;
您应该执行类似的操作:
auto t1 = std::chrono::steady_clock::now();
//do some work
auto t2 = std::chrono::steady_clock::now();
double duration_in_seconds = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1).count();
请注意,我将持续时间延长了一倍。 然后,您可以更自由地使用持续时间值。
如果您更喜欢纳秒:
double duration_in_nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.