在c ++中以优雅的方式定时 [英] Timing in an elegant way in c++

查看:92
本文介绍了在c ++中以优雅的方式定时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣在计算自由函数或成员函数(模板或不是)的执行时间。调用TheFunc函数,它的调用是

I am interested in timing the execution time of a free function or a member function (template or not). Call TheFunc the function in question, its call being

TheFunc(/*parameters*/);

ReturnType ret = TheFunc(/*parameters*/);

当然,我可以如下包装这些函数调用:

Of course I could wrap these function calls as follows :

double duration = 0.0 ;
std::clock_t start = std::clock();
TheFunc(/*parameters*/);
duration = static_cast<double>(std::clock() - start) / static_cast<double>(CLOCKS_PER_SEC);

double duration = 0.0 ;
std::clock_t start = std::clock();
ReturnType ret = TheFunc(/*parameters*/);
duration = static_cast<double>(std::clock() - start) / static_cast<double>(CLOCKS_PER_SEC);

但我想做一些比这更优雅的东西,到void返回类型)如下:

but I would like to do something more elegant than this, namely (and from now on I will stick to the void return type) as follows :

Timer thetimer ;
double duration = 0.0;
thetimer(*TheFunc)(/*parameters*/, duration);

其中Timer是一些我想设计的时序类,代码,这样在执行前面代码的最后一行之后,双重持续时间将包含

where Timer is some timing class that I would like to design and that would allow me to write the previous code, in such way that after the exectution of the last line of previous code the double duration will contain the execution time of

TheFunc(/*parameters*/);

但我不知道如何做到这一点,最佳...

but I don't see how to do this, nor if the syntax/solution I aim for is optimal...

推荐答案

使用可变参数模板,您可以:

With variadic template, you may do:

template <typename F, typename ... Ts>
double Time_function(F&& f, Ts&&...args)
{
    std::clock_t start = std::clock();
    std::forward<F>(f)(std::forward<Ts>(args)...);
    return static_cast<double>(std::clock() - start) / static_cast<double>(CLOCKS_PER_SEC);
}

这篇关于在c ++中以优雅的方式定时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆