【发布时间】:2014-06-28 15:39:42
【问题描述】:
我尝试构建一个可以测量任意类型函数的执行时间的函数模板。到目前为止,这是我尝试过的:
#include <chrono>
#include <iostream>
#include <type_traits>
#include <utility>
// Executes fn with arguments args and returns the time needed
// and the result of f if it is not void
template <class Fn, class... Args>
auto timer(Fn fn, Args... args)
-> std::pair<double, decltype(fn(args...))> {
static_assert(!std::is_void<decltype(fn(args...))>::value,
"Call timer_void if return type is void!");
auto start = std::chrono::high_resolution_clock::now();
auto ret = fn(args...);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
return { elapsed_seconds.count(), ret };
}
// If fn returns void, only the time is returned
template <class Fn, class... Args>
double timer_void(Fn fn, Args... args) {
static_assert(std::is_void<decltype(fn(args...))>::value,
"Call timer for non void return type");
auto start = std::chrono::high_resolution_clock::now();
fn(args...);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
return elapsed_seconds.count();
}
int main () {
//This call is ambigous if the templates have the same name
std::cout << timer([](double a, double b){return a*b;},1,2).first;
}
请注意,对于void(...) 函数,我必须有一个具有不同名称的函数。有没有办法摆脱第二个功能?
(我一开始做的对吗?)
【问题讨论】:
-
不,这是不正确的(温和的) - 你应该制作一个简单的工作测试用例,其中包含所有包含和主要的
-
未经测试的代码就是不工作的代码
-
@YePhIcK 它适用于示例,但这并不意味着它是正确的。
-
我认为你应该在codereview.stackexchange.com 发帖。
-
@RSahu 我认为它属于这里,因为它不像我想要的那样工作(即不需要两个不同的名称)。我不会就我的风格等寻求建议(尽管当然总是受欢迎的)。编辑:重新阅读 codereview 的规则,这似乎是主题。所以如果那里更合适,我可以搬家吗?
标签: c++ templates c++11 variadic-templates chrono