You can use a lambda with auto
parameters in C++14 to time your other functions. You can pass the parameters of the timed function to your lambda. I'd do it like this:
// Timing in C++14 with auto lambda parameters
#include <iostream>
#include <chrono>
// need C++14 for auto lambda parameters
auto timing = [](auto && F, auto && ... params)
{
auto start = std::chrono::steady_clock::now();
std::forward<decltype(F)>(F)
(std::forward<decltype(params)>(params)...); // execute the function
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start).count();
};
void f(std::size_t numsteps) // we'll measure how long this function runs
{
// need volatile, otherwise the compiler optimizes the loop
for (volatile std::size_t i = 0; i < numsteps; ++i);
}
int main()
{
auto taken = timing(f, 500'000'000); // measure the time taken to run f()
std::cout << "Took " << taken << " milliseconds" << std::endl;
taken = timing(f, 100'000'000); // measure again
std::cout << "Took " << taken << " milliseconds" << std::endl;
}
The advantage is that you can pass any callable object to the timing
lambda.
But if you want to keep it simple, you can just do:
auto start = std::chrono::steady_clock::now();
your_function_call_here();
auto end = std::chrono::steady_clock::now();
auto taken = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
std::cout << taken << " milliseconds";
If you know you're not going to change the system time during the run, you can use a std::chrono::high_resolution_clock
instead, which may be more precise. std::chrono::steady_clock
is however un-sensitive to system time changes during the run.
PS: In case you need to time a member function, you can do:
// time member functions
template<class Return, class Object, class... Params1, class... Params2>
auto timing(Return (Object::*fp)(Params1...), Params2... params)
{
auto start = std::chrono::steady_clock::now();
(Object{}.*fp)(std::forward<decltype(params)>(params)...);
return std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start).count();
};
then use it as
// measure the time taken to run X::f()
auto taken = timing(&X::f, 500'000'000);
std::cout << "Took " << taken << " milliseconds" << std::endl;
to time e.g. X::f()
member function.