首页 > 解决方案 > 如何添加在循环内执行函数所需的时间?

问题描述

我有两个函数的实现,想看看哪个更快。打电话给他们foo1()foo2()。我有一组测试用例我想针对它们运行。测试用例存储在一个数组中,我不想包括访问数组所花费的时间。这是我的代码。它不会编译duration += std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 )并显示错误消息error: no match for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'std::chrono::microseconds' {aka 'std::chrono::duration<long long int, std::ratio<1, 1000000> >'}) 52 | std::cout << "duration: " << duration << std::endl;

代码:

/*[first argument, second argument, correct result]*/
 int inout[5][3] = {
    {10, 4, 5},
    {21, 4, 6},
    {22, 4, 7},
    {50, 5, 19},
    {100, 5, 7},
    //just example, real one is longer


};

std::chrono::microseconds duration = std::chrono::microseconds::zero();
for(auto& i : inout)
{
    auto t1 = std::chrono::high_resolution_clock::now();
    foo1(i[0], i[1]);
    auto t2 = std::chrono::high_resolution_clock::now();
    duration += std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();//this won't compile
}
std::cout << "duration of foo1(): " << duration << std::endl;

duration = std::chrono::microseconds::zero();
for(auto& i : inout)
{
    auto t1 = std::chrono::high_resolution_clock::now();
    foo2(i[0], i[1]);
    auto t2 = std::chrono::high_resolution_clock::now();
    duration += std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();//this won't compile
}
std::cout << "duration of foo2(): " << duration << std::endl;

对这里的任何事情有什么建议吗?我在想测试缓存未命中的速度更有意义,所以应该交错调用foo1()和调用吗?foo2()OTOH 的目标是查看哪个更快,并且两者都将从缓存中受益,但是较大的可能会有更多的缓存未命中。出于好奇auto& i,foreach 循环中的类型是什么?

标签: c++benchmarkingchrono

解决方案


这可能是这样的:

std::chrono::microseconds duration = std::chrono::microseconds::zero();
for (auto &i : inout) {
  auto t1 = std::chrono::high_resolution_clock::now();
  // f1()
  auto t2 = std::chrono::high_resolution_clock::now();
  duration += std::chrono::duration_cast<std::chrono::microseconds>(
      t2 - t1);
}
std::cout << "duration of foo1(): " << duration.count() << std::endl;

duration = std::chrono::microseconds::zero();
for (auto &i : inout) {
  auto t1 = std::chrono::high_resolution_clock::now();
  // f2()
  auto t2 = std::chrono::high_resolution_clock::now();
  duration += std::chrono::duration_cast<std::chrono::microseconds>(
      t2 - t1);
}
std::cout << "duration of foo2(): " << duration.count() << std::endl;
}

一些解释:如果您有错误消息,例如

<source>:23:14: error: no match for 'operator+=' (operand types are 'std::chrono::microseconds' {aka 'std::chrono::duration<long int, std::ratio<1, 1000000> >'} and 'std::chrono::duration<long int, std::ratio<1, 1000000> >::rep' {aka 'long int'})

   23 |     duration += std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();

microseconds您可以看到and没有运算符long int。因此,您可以转到文档并查看持续时间有哪些运算符,您会找到https://en.cppreference.com/w/cpp/chrono/duration/operator_arith3

你看到你必须通过另一个持续时间,所以你不应该count()在那里打电话。


推荐阅读