Search code examples
c++timing

timing of multiple function calls


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;
 }

which could be used like:

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

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

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


Solution

  • 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;
    }
    

    But simply

    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;
    }
    

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

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