making time measurement for class methodes

70 views Asked by At

I have written class for measure function run time. and its works fine. However when I start to use it in my project to measure speed of classes method, it breaks with the following error:

error: invalid use of non-static member function

this is my measure function:

template<typename F, typename... Args>
    decltype(auto) Time::timer(F function, Args&&... args){

    auto start = std::chrono::steady_clock::now();

    auto ret = function(std::forward<Args>(args)...);

    auto end = std::chrono::steady_clock::now();
    std::chrono::duration<double> elapsed_seconds = end-start;
    std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";

    return ret; 
}

how can i pass class method to my function, or how can i write function that measure class method speed?

1

There are 1 answers

0
Woodford On

The simplest solution is to just wrap the call to your member function in a lambda and pass that as the function argument to Time::timer:

struct Foo {
    double bar(double d) { return d; }
};

// ...
Foo f;
auto result = Time::timer([&f]{return f.bar(3.1415);});

Alternatively, you can call the member function directly if you add an overload for Time::timer:

template<typename F, typename T, typename... Args>
decltype(auto) timer(F&& func, T& obj, Args&&... args){
    auto start = std::chrono::steady_clock::now();

    auto ret = (obj.*func)(std::forward<Args>(args)...);  // call member fn

    auto end = std::chrono::steady_clock::now();
    std::chrono::duration<double> elapsed_seconds = end-start;
    std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";
    return ret; 
}

// ...
Foo f;
auto result = Time::timer(&Foo::bar, f, 3.1415);