测量函数的执行时间

Stelios Daveas

我想测量函数执行的时间。

我可以这样使用:

using namespace std::chrono;
auto start = steady_clock::now();
// process
auto end = duration<double>(steady_clock::now() - start).count();

但对我来说,我似乎一点也不干所以我创建了一个小函数来做到这一点:

template <typename Function, typename... Args>
auto measure_time(Function func, Args&&... args)
{
    using namespace std::chrono;
    auto start = steady_clock::now();
    func(std::forward<Args>(args)...);   // handle lvalues and rvalues
    return duration<double>(steady_clock::now() - start).count();
}

我这样称呼它:

measure_time(func, arg1, arg2, arg3);       // for common functions
measure_time([](){func(arg1,arg2, arg3););  // for member or template functions

这对我来说很好,但确实有一些缺点:

  1. 对我来说,尚不清楚如何方便地更改以同时检索返回值func(当然也可以是void)?
  2. 这显然与功能一一法则相抵触
  3. 代码的可读性被大大破坏:
    important_function(arg1, arg2);                // reads well
    measure_time(important_function, arg1, arg2);  // measure_time steals the spotlight 
    

有面对这些问题的指导方针吗?


更新:

我忘了提一下,执行该功能后,我需要将经过的时间存储到一个容器中。


更新2:

在@puio的答案之后,我最终得到了这个:

using namespace std::chrono;
template <typename Container>
class Timer{
   public:
    Timer(Container& _c) : c(_c) {}
    ~Timer() {
        c.push_back(duration<float>(steady_clock::now() - start).count());
    }
   private:
    time_point<steady_clock> start{steady_clock::now()};
    Container& c;
};

用法:

auto mc = MyContainer{};
...
{
    auto t = Timer<MyContainer>(mc);
    // things to measure
}
// mc.back() is the elapsed time

干燥并清洁:)

io

在函数中实例化此类,它将显示对象超出范围的时间。

class Timer {
 private:
  std::chrono::steady_clock::time_point begin;
  std::string_view func_name;

 public:
  Timer(std::string_view func)
  {
    func_name = func;
    begin = std::chrono::steady_clock::now();
  }
  ~Timer()
  {
    const std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
    std::cout << func_name << " Time: "
              << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()
              << " microseconds " << std::endl;
  }
};

用法:

void slow_func(){
  Timer timer{__func__};
  // ...
  // Destruct automatically.
}

chrono因为我一直忘了它,所以这里采取功能。


但是我需要将经过的时间存储在一个容器中

我想是这样std::vector,通过非常量引用(作为返回值)将其传递给构造函数,将引用存储在private访问中,并将push_back向量的时间存储在析构函数中。

这样做的公共成员函数,或者用std::vector后者显式调用析构函数,只会使其变得麻烦。同样,呼叫者可能会错过使用该功能的机会。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章