【发布时间】:2019-08-13 13:58:40
【问题描述】:
我正在尝试编写一个函数,该函数接受任何其他任意函数作为输入并对其计时,然后返回该函数的结果。我已经研究了几个小时,并且认为我已经很接近了,但我仍然无法弄清楚如何编译它。
这是我目前所拥有的:
// Some arbitrary function to pass to the timer
int DoSomething(int x, double y)
{
// Does something with x and y
return 0;
}
// Function used to time another function and return its result
template <typename T, typename Function, typename... Args>
T GetRuntime(const std::string& name, const Function& function, Args&&... args)
{
std::cout << name << " started..." << std::endl;
auto start = std::chrono::high_resolution_clock::now();
T result = function(std::forward<Args>(args)...);
auto stop = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start);
std::cout << name << " complete - duration: " << duration.count() << " milliseconds." << std::endl;
return result;
}
int main()
{
// Doesn't compile
int output = GetRuntime("DoSomething", DoSomething, 42, 42.42);
}
我是否以正确的方式处理这个问题?如果是这样,我需要改变什么才能使这项工作?如果不是,有什么更好的方法来解决这个问题?
【问题讨论】:
-
您可以通过创建一个作用域计时器稍有不同,并将其添加到您要调用的函数的顶部。构造函数将启动计时器,析构函数将停止它并打印持续时间。您需要在函数开头编写的唯一代码是
ScopedTimer timer()
标签: c++ templates generic-programming