C++ Logo

std-proposals

Advanced search

measure execution time of a function

From: Paul Raffer <paul.raffer_at_[hidden]>
Date: Sat, 17 Jul 2021 21:41:20 +0000
Some weeks ago I asked if there is the need for a function which measures the execution time of another function, but nobody responded. Could you please give me a short feedback.

Possible implementation:
template <typename Duration, typename Result>
struct measurement_result {
Duration duration;
Result result;
};

template <
typename Clock = std::chrono::high_resolution_clock,
typename F, typename... Args>
auto measure_ignore_result(F f, Args&&... args)
{
auto const start = Clock::now();
f(std::forward<Args>(args)...);
auto const stop = Clock::now();
auto const duration = stop - start;
return measurement_result<decltype(duration), std::monostate>{duration};
}
template <
typename Clock = std::chrono::high_resolution_clock,
typename F, typename... Args,
std::enable_if_t<std::is_void_v<std::result_of_t<F(Args...)>>, bool> = true>
auto measure(F f, Args&&... args)
{
return measure_ignore_result(
std::forward<F>(f), std::forward<Args>(args)...);
}
template <
typename Clock = std::chrono::high_resolution_clock,
typename F, typename... Args,
std::enable_if_t<!std::is_void_v<std::result_of_t<F(Args...)>>, bool> = true>
auto measure(F f, Args&&... args)
{
auto const start = Clock::now();
auto const result = f(std::forward<Args>(args)...);
auto const stop = Clock::now();
auto const duration = stop - start;
return measurement_result{duration, result};
}

Usage:

auto fib(int i) -> int
{
return i <= 1 ? i : fib(i-1) + fib(i-2);
}

auto main() -> int
{
std::cout << std::chrono::duration<double>(measure(fib, 42).duration).count();
}

Paul Raffer

Received on 2021-07-17 16:41:28