C++ Logo

std-proposals

Advanced search

Re: measure execution time of a function

From: Paul Raffer <paul.raffer_at_[hidden]>
Date: Wed, 28 Jul 2021 16:30:31 +0000
Ok, you are right Edward. But is there a proposal, that tries to standardize such a benchmarking library?

Paul

‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
On Sunday, July 18th, 2021 at 11:18, Edward Catmur <ecatmur_at_[hidden]> wrote:

> What's the situation where you would want to use this function but not need the additional facilities (baseline, warmup, statistical analysis) of a fully-fledged (micro-)benchmarking library?
>
> https://www.bfilipek.com/2016/01/micro-benchmarking-libraries-for-c.html
>
> On Sat, 17 Jul 2021 at 22:41, Paul Raffer via Std-Proposals <std-proposals_at_[hidden]> wrote:
>
>> 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
>>
>> --
>> Std-Proposals mailing list
>> Std-Proposals_at_[hidden]
>> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2021-07-28 11:30:39