Search code examples
c++timing

Timing in an elegant way in c++


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*/);

or

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);

or

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);

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);

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...


Solution

  • 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);
    }