I wanted to have a function called timeit which can measure the time of execution of n iterations of any other function. I still learning C++ but I come up with that : Any thought ?


using namespace std;

template<typename output, typename ...ArgsT, typename ...Input>
double timeit(output (*function)(Input...), int n, ArgsT ...args)
   auto start = chrono::high_resolution_clock::now();
   for(int k = 0; k < n; ++k)
   auto end = chrono::high_resolution_clock::now();
   chrono::duration<double> elapsed = (end-start);
   return elapsed.count();

1 Answer 1


The big thing you're missing here is perfect forwarding. When you receive the argument pack, it may contain one or more rvalue references. But when you pass args... to the function you're timing, you've given a name to the pack, so even though what you received were rvalue references, what you end up passing to the timed function won't be an rvalue reference any more.

To fix this, you'd use std::forward:


The other obvious addition I'd consider would be gathering and returning the return values from the calls you make. One possibility would be to return something like a pair<double, std::vector<output>>, to hold the time and the return values.

  • \$\begingroup\$ Thank you for your answer, I will look into std::forward. It was me first time using argument pack so i did not think about passing by references. \$\endgroup\$
    – ThomasL
    Commented Mar 28, 2021 at 20:33
  • \$\begingroup\$ @ThomasL: For a first attempt at something, I'd say you did admirably well (quite a lot better than my first attempt, anyway). \$\endgroup\$ Commented Mar 28, 2021 at 20:39
  • \$\begingroup\$ Thank you I am sure you do well too. \$\endgroup\$
    – ThomasL
    Commented Mar 28, 2021 at 20:42
  • \$\begingroup\$ @ThomasL: I've done better since, but my first attempt was pretty ugly. :-) \$\endgroup\$ Commented Mar 28, 2021 at 20:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.