我想将一个函数作为参数传递给执行该函数的包装函数,计算执行时间并打印它,然后返回该函数的返回值。这是我到目前为止尝试做的。
#include <functional>
#include <chrono>
namespace TimeIt {
template <typename T>
auto time_it(std::string name, std::function<T> work) -> decltype(work()) {
auto start = std::chrono::high_resolution_clock::now();
auto return_value = work();
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
printf("Time taken by function:%s is %lld",name, duration.count());
return return_value;
}
}
最佳答案
在这里尝试将所有内容包装在 std::function
中是非常有害的,您应该只推导原始的可调用类型。
template <typename Callable, typename ... Args>
auto time_it(std::string name, Callable&& work, Args&&... args) -> std::invoke_result_t<Callable, Args...> {
auto start = std::chrono::high_resolution_clock::now();
auto return_value = std::invoke(std::forward<Callable>(work), std::forward<Args>(args)...);
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
printf("Time taken by function:%s is %lld",name, duration.count());
return return_value;
}
关于c++ - 尝试将任何函数作为参数发送并推断类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53229335/