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 ?
#include<chrono>
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)
{
function(args...);
}
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
:
function(std::forward<ArgsT>(args)...);
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– ThomasL2021年03月28日 20:33:27 +00:00Commented 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\$Jerry Coffin– Jerry Coffin2021年03月28日 20:39:40 +00:00Commented Mar 28, 2021 at 20:39
-
\$\begingroup\$ Thank you I am sure you do well too. \$\endgroup\$ThomasL– ThomasL2021年03月28日 20:42:40 +00:00Commented Mar 28, 2021 at 20:42
-
\$\begingroup\$ @ThomasL: I've done better since, but my first attempt was pretty ugly. :-) \$\endgroup\$Jerry Coffin– Jerry Coffin2021年03月28日 20:44:34 +00:00Commented Mar 28, 2021 at 20:44