我想测量函数执行的时间。
我可以使用这样的东西:
using namespace std::chrono;
auto start = steady_clock::now();
// process
auto end = duration<double>(steady_clock::now() - start).count();
但我看起来很不- DRY大部头书。所以我创建了一个小函数来完成它:
template <typename Function, typename... Args>
auto measure_time(Function func, Args&&... args)
{
using namespace std::chrono;
auto start = steady_clock::now();
func(std::forward<Args>(args)...); // handle lvalues and rvalues
return duration<double>(steady_clock::now() - start).count();
}
我这样调用它:
measure_time(func, arg1, arg2, arg3); // for common functions
measure_time([](){func(arg1,arg2, arg3);); // for member or template functions
这对我来说效果很好,但它确实有一些缺点:
- 我不清楚如何方便地更改它以检索
func
的返回值(当然,也可以是void
)? - 这显然与每个功能一件事的规则相矛盾
- 代码的可读性被严重削弱:
important_function(arg1, arg2); // reads well measure_time(important_function, arg1, arg2); // measure_time steals the spotlight
是否有任何指南可以应对这些问题?
更新:
我忘了提到,在执行函数后,我需要将耗时存储到容器中。
更新 2:
在 @puio 的回答之后,我得到了这个:
using namespace std::chrono;
template <typename Container>
class Timer{
public:
Timer(Container& _c) : c(_c) {}
~Timer() {
c.push_back(duration<float>(steady_clock::now() - start).count());
}
private:
time_point<steady_clock> start{steady_clock::now()};
Container& c;
};
用法:
auto mc = MyContainer{};
...
{
auto t = Timer<MyContainer>(mc);
// things to measure
}
// mc.back() is the elapsed time
干燥和清洁:)
最佳答案
在函数中实例化此类,当对象超出范围时,它将打印时间。
class Timer {
private:
std::chrono::steady_clock::time_point begin;
std::string_view func_name;
public:
Timer(std::string_view func)
{
func_name = func;
begin = std::chrono::steady_clock::now();
}
~Timer()
{
const std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
std::cout << func_name << " Time: "
<< std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count()
<< " microseconds " << std::endl;
}
};
用法:
void slow_func(){
Timer timer{__func__};
// ...
// Destruct automatically.
}
chrono
函数取自这里,因为我一直忘记它。
But I need to store the time elapsed in a container
我想象它是std::vector
,通过非常量引用(作为返回值)将其传递给构造函数,将引用存储在private
访问中, push_back
析构函数中 vector 的时间。
执行此操作的公共(public)成员函数,或使用所述 std::vector 显式调用析构函数只会使其变得麻烦。此外,调用者可能会错过使用该功能。
关于c++ - 测量函数的执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63614208/