多个函数调用的时序 [英] timing of multiple function calls

查看:301
本文介绍了多个函数调用的时序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自python我试图找到一种方法来计时一些c ++代码中的函数调用。到目前为止我使用这个。

Coming from python I am trying to find a way to time several function calls in a c++ code. So far I am using this.

 void my_func(/*some args*/) {
   clock_t t_begin = std::clock();
   // code
   clock_t t_end = std::clock();
   double elapsed_secs_U = double(t_end - t_begin) / CLOCKS_PER_SEC;
 }

但这是高度重复的。我想有一个类似函数包装的东西,所以我可以写:

But this is highly repetitive. And I would like to have something like a function wrapper so that I can write:

 void timer(func, *args) {
   clock_t t_begin = std::clock();
   func(*args)
   clock_t t_end = std::clock();
   double elapsed_secs_U = double(t_end - t_begin) / CLOCKS_PER_SEC;
 }

可以像下面这样使用:

 timer(compute_a, a, b)
 timer(compute_b, b, c)

有没有办法在C ++中实现这个?

Is there any way to achieve this in C++?

PS:我需要在生产运行中的时间,不要使用剖析标志重新编译我的代码并将其粘贴到Valgrind或任何其他工具

PS: I need the timings in productive runs, thus I dont want to recompile my code with profiling flags and stick it into Valgrind or any other tool

推荐答案

使用可变参数模板,例如:

Using variadic template, you may do something like:

template <typename F, typename ... Ts>
void timer(F f, Ts&&...args) {
   clock_t t_begin = std::clock();
   f(std::forward<Ts>(args)...);
   clock_t t_end = std::clock();
   double elapsed_secs_U = double(t_end - t_begin) / CLOCKS_PER_SEC;
}

但只需

template <typename F>
void timer(F f) {
   clock_t t_begin = std::clock();
   f();
   clock_t t_end = std::clock();
   double elapsed_secs_U = double(t_end - t_begin) / CLOCKS_PER_SEC;
}

应该执行此任务,并在需要传递参数时传递捕获lambda:

should do the job, and pass capturing lambda when you need to pass argument:

timer([&](){ compute_b(b, c);});

这篇关于多个函数调用的时序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆