首页 > 解决方案 > 为类方法进行时间测量

问题描述

我已经为测量函数运行时间编写了类。它的工作正常。但是,当我开始在我的项目中使用它来测量类方法的速度时,它会因以下错误而中断:

错误:无效使用非静态成员函数

这是我的测量功能:

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

我如何将类方法传递给我的函数,或者我如何编写测量类方法速度的函数?

标签: c++templatesmethodsperfect-forwardingtime-measurement

解决方案


最简单的解决方案是将对成员函数的调用包装在 lambda 中,并将其作为函数参数传递给Time::timer

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

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

或者,如果您添加重载,则可以直接调用成员函数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);

推荐阅读