我想制作一个benchmark
函数,给定一个invocable及其参数,该函数将计时该给定invocable的执行,并返回测得的std::chrono::duration<...>
以及调用时返回的值令人难以忘怀。
我无法完美地转发从调用返回的值。当前,我返回调用返回的值,并使用引用参数返回持续时间:
using bench_clock = std::conditional_t<std::chrono::high_resolution_clock::is_steady,
std::chrono::high_resolution_clock, std::chrono::steady_clock>;
decltype(auto) benchmark(
bench_clock::duration& duration, auto&& func, auto&&... args)
{
auto begin{ bench_clock::now() };
decltype(auto) result{
std::invoke(
std::forward<decltype(func)>(func),
std::forward<decltype(args)>(args)...)
};
duration = bench_clock::now() - begin;
return result;
}
据我所知,这完美地转发了调用返回的值。
例如,我更愿意使用std::tuple
返回常规持续时间,尽管我不确定如何完美地转发返回值。
我的猜测是像这样使用std::invoke_result_t
:
using bench_clock = std::conditional_t<
std::chrono::high_resolution_clock::is_steady,
std::chrono::high_resolution_clock, std::chrono::steady_clock>;
auto benchmark(auto&& func, auto&&... args)
{
auto begin{ bench_clock::now() };
decltype(auto) result{
std::invoke(
std::forward<decltype(func)>(func),
std::forward<decltype(args)>(args)...)
};
auto duration{ bench_clock::now() - begin };
return std::tuple<std::invoke_result_t<decltype(func), decltype(args)...>, bench_clock::duration>{std::forward<decltype(result)>(result), duration};
//------------------------------------------------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ is this needed?
}
我不确定这种方法是否正确地向前发展。我也不知道是否需要在std::forward
构造函数中使用std::tuple
。
还有一个问题,如果可调用对象返回void
,则无法使用元组,因为无法实例化std::tuple<void>
。
我不确定该如何解决。
答案 0 :(得分:3)
是的,您是正确的。在void
函数内调用函数func
时,需要处理benchmark
返回情况。
由于您使用过std::invoke_result_t
和std::conditional_t
,因此我假设您可以访问c++17。然后可以通过if constexpr
检查来轻松解决。
#include <iostream>
#include <chrono>
#include <tuple>
#include <type_traits> // std::is_same_v, std::invoke_result_t
#include <functional> // std::invoke
#include <utility> // std::forward, std::move
using namespace std::chrono;
using bench_clock = std::conditional_t<
high_resolution_clock::is_steady, high_resolution_clock, steady_clock>;
template<typename Func, typename... Args>
decltype(auto) benchmark(Func&& func, Args&&... args)
{
auto begin{ bench_clock::now() };
if constexpr (std::is_same_v<void, std::invoke_result_t<Func, Args...>>)
{
// can not have void result: therefore just invoke the func!
std::invoke(std::forward<Func>(func), std::forward<Args>(args)...);
return bench_clock::now() - begin; // only the time duration will be returned!
}
else
{
// all other cases return the tuple of result-duration!
decltype(auto) result{ std::invoke(std::forward<Func>(func), std::forward<Args>(args)...) };
const auto duration{ bench_clock::now() - begin };
return std::make_tuple(std::move(result), duration);
}
}