Just want to throw in the modern approach to timing any callable using <chrono>
and the handy std::invoke
from C++17. Works on members, lambdas or free function, or any other callable.
// Just for convenience
using Seconds = std::chrono::duration<double>;
// Measure how much time the given function takes to execute using chrono
// Pass the function name, then all relevant arguments, including the object as the first if it's a member function
template<typename Function, typename... Args>
Seconds measure(Function&& toTime, Args&&... a)
{
auto start{std::chrono::steady_clock::now()}; // Start timer
std::invoke(std::forward<Function>(toTime), std::forward<Args>(a)...); // Forward and call
auto stop{std::chrono::steady_clock::now()}; // Stop timer
return (stop - start);
}
This will return the time the function took to execute. If you also need the return value, you could make a std::pair
with the Seconds
and the return value since std::invoke
will correctly return what the callable returns.
Then you can use it like this:
auto t1 = measure(normalFunction);
auto t2 = measure(&X::memberFunction, obj, 4);
auto t3 = measure(lambda, 2, 3);
On a free function, member function and lambda respectively.