0

I want to measure the execution time of methods and found the following Topic:

Easily measure elapsed time

There exists an answer for measuring the function execution time with

#include <iostream>
#include <chrono>

template<typename TimeT = std::chrono::milliseconds>
struct measure
{
    template<typename F, typename ...Args>
    static typename TimeT::rep execution(F func, Args&&... args)
    {
        auto start = std::chrono::system_clock::now();
        func(std::forward<Args>(args)...);
        auto duration = std::chrono::duration_cast< TimeT> 
                            (std::chrono::system_clock::now() - start);
        return duration.count();
    }
};

int main() {
    std::cout << measure<>::execution(functor(dummy)) << std::endl;
}

Is it possible to use this code for method measurement? How can i change the template types to pass a method and an object like

measure<>::execution(object, method);

or better

measure<>::execution(object.method(param));

By now, i have the following result:

struct measure
{
    template<class T, typename R>
    static R execution(T& obj, R(T::*func)())
    {
        auto start = std::chrono::system_clock::now();
        R result = (obj.*func)();
        auto duration = std::chrono::duration_cast<std::chrono::microseconds>
                            (std::chrono::system_clock::now() - start);
        return result;
    }
};

But i don't know how to pass Args and use it as shown in the example above. I have to execute

measure::execution(obj, method);
Community
  • 1
  • 1
  • have you tried anything? where's your attempt? – Karoly Horvath Jul 14 '15 at 07:06
  • note that arguments are evaluated first, so `object.method(param)` won't work. – Karoly Horvath Jul 14 '15 at 07:07
  • Thank you for comment! I have updated the question – Tobias Braun Jul 14 '15 at 14:05
  • I've found it useful to make a `timer` class that initializes a `std::chrono::time_point` (or other clock) in its constructor, and in its destructor take the current time and display how much time has elapsed. – Alejandro Jul 14 '15 at 14:08
  • @TobiasBraun, You can use `std::mem_fn` to wrap your pointer-to-member into a callable that can be used with the first version of `measure<>::execution`. The call would look like `measure<>::execution(std::mem_fn(ptr_to_member),object);` – Alejandro Jul 14 '15 at 14:23

0 Answers0