在c ++中以优雅的方式进行计时

Olo*_*rin 6 c++ timing

我感兴趣的是计算自由函数或成员函数(模板与否)的执行时间.调用TheFunc有问题的函数,它的调用是

TheFunc(/*parameters*/);
Run Code Online (Sandbox Code Playgroud)

要么

ReturnType ret = TheFunc(/*parameters*/);
Run Code Online (Sandbox Code Playgroud)

当然我可以按如下方式包装这些函数调用:

double duration = 0.0 ;
std::clock_t start = std::clock();
TheFunc(/*parameters*/);
duration = static_cast<double>(std::clock() - start) / static_cast<double>(CLOCKS_PER_SEC);
Run Code Online (Sandbox Code Playgroud)

要么

double duration = 0.0 ;
std::clock_t start = std::clock();
ReturnType ret = TheFunc(/*parameters*/);
duration = static_cast<double>(std::clock() - start) / static_cast<double>(CLOCKS_PER_SEC);
Run Code Online (Sandbox Code Playgroud)

但是我想做一些比这更优雅的事情,即(从现在起我将坚持使用void返回类型)如下:

Timer thetimer ;
double duration = 0.0;
thetimer(*TheFunc)(/*parameters*/, duration);
Run Code Online (Sandbox Code Playgroud)

其中Timer是我想设计的一些时序类,这将允许我编写前面的代码,这样在前面代码的最后一行的exectution之后,double duration将包含执行时间

TheFunc(/*parameters*/);
Run Code Online (Sandbox Code Playgroud)

但我不知道如何做到这一点,也不是我的目标语法/解决方案是最佳的...

Jar*_*d42 7

使用可变参数模板,您可以:

template <typename F, typename ... Ts>
double Time_function(F&& f, Ts&&...args)
{
    std::clock_t start = std::clock();
    std::forward<F>(f)(std::forward<Ts>(args)...);
    return static_cast<double>(std::clock() - start) / static_cast<double>(CLOCKS_PER_SEC);
}
Run Code Online (Sandbox Code Playgroud)


Esc*_*alo 5

我真的很喜欢boost::cpu_timer::auto_cpu_timer,当我不能使用boost时,我就简单地破解自己的:

#include <cmath>
#include <string>
#include <chrono>
#include <iostream>

class AutoProfiler {
 public:
  AutoProfiler(std::string name)
      : m_name(std::move(name)),
        m_beg(std::chrono::high_resolution_clock::now()) { }
  ~AutoProfiler() {
    auto end = std::chrono::high_resolution_clock::now();
    auto dur = std::chrono::duration_cast<std::chrono::microseconds>(end - m_beg);
    std::cout << m_name << " : " << dur.count() << " musec\n";
  }
 private:
  std::string m_name;
  std::chrono::time_point<std::chrono::high_resolution_clock> m_beg;
};

void foo(std::size_t N) {
  long double x {1.234e5};
  for(std::size_t k = 0; k < N; k++) {
    x += std::sqrt(x);
  }  
}


int main() {
  {
    AutoProfiler p("N = 10");
    foo(10);
  }

  {
    AutoProfiler p("N = 1,000,000");
    foo(1000000);
  }

}
Run Code Online (Sandbox Code Playgroud)

感谢RAII,该计时器可以工作。在范围内构建对象时,将在该时间点存储时间点。当您离开示波器(即在处})时,计时器首先存储时间点,然后计算滴答数(您可以将其转换为人类可以理解的持续时间),最后将其打印到屏幕上。

当然,boost::timer::auto_cpu_timer比简单的实现要复杂得多,但是我经常发现实现对我的目的绰绰有余。

示例在我的计算机上运行:

$ g++ -o example example.com -std=c++14 -Wall -Wextra
$ ./example
N = 10 : 0 musec
N = 1,000,000 : 10103 musec
Run Code Online (Sandbox Code Playgroud)

编辑

我真的很喜欢@ Jarod42建议的实现。我对其进行了一些修改,以在所需的输出“单位”上提供一定的灵活性。

默认情况下,它返回经过的微秒数(通常是一个整数std::size_t),但是您可以要求输出在您选择的任何持续时间内。

我认为这是一种比我之前建议的方法更灵活的方法,因为现在我可以做其他事情,例如进行测量并将其存储在容器中(就像在示例中所做的那样)。

感谢@ Jarod42的启发。

#include <cmath>
#include <string>
#include <chrono>
#include <algorithm>
#include <iostream>

template<typename Duration = std::chrono::microseconds,
         typename F,
         typename ... Args>
typename Duration::rep profile(F&& fun,  Args&&... args) {
  const auto beg = std::chrono::high_resolution_clock::now();
  std::forward<F>(fun)(std::forward<Args>(args)...);
  const auto end = std::chrono::high_resolution_clock::now();
  return std::chrono::duration_cast<Duration>(end - beg).count();
}

void foo(std::size_t N) {
  long double x {1.234e5};
  for(std::size_t k = 0; k < N; k++) {
    x += std::sqrt(x);
  }
}

int main() {
  std::size_t N { 1000000 };

  // profile in default mode (microseconds)
  std::cout << "foo(1E6) takes " << profile(foo, N) << " microseconds" << std::endl;

  // profile in custom mode (e.g, milliseconds)
  std::cout << "foo(1E6) takes " << profile<std::chrono::milliseconds>(foo, N) << " milliseconds" << std::endl;

  // To create an average of `M` runs we can create a vector to hold
  // `M` values of the type used by the clock representation, fill
  // them with the samples, and take the average
  std::size_t M {100};
  std::vector<typename std::chrono::milliseconds::rep> samples(M);
  for(auto & sample : samples) {
    sample = profile(foo, N);
  }
  auto avg = std::accumulate(samples.begin(), samples.end(), 0) / static_cast<long double>(M);
  std::cout << "average of " << M << " runs: " << avg << " microseconds" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

输出(与编译g++ example.cpp -std=c++14 -Wall -Wextra -O3):

foo(1E6) takes 10073 microseconds
foo(1E6) takes 10 milliseconds
average of 100 runs: 10068.6 microseconds
Run Code Online (Sandbox Code Playgroud)