【问题标题】:making time measurement for class methodes为类方法进行时间测量
【发布时间】:2021-03-31 18:55:22
【问题描述】:

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

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

这是我的测量函数:

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

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

【问题讨论】:

  • 将您的成员函数调用包装在 lambda 中
  • 当我开始在我的项目中使用它来测量类方法的速度时,它会中断它是如何中断的?
  • drescherjm,错误:非静态成员函数的使用无效

标签: c++ templates methods perfect-forwarding time-measurement


【解决方案1】:

最简单的解决方案是将对成员函数的调用包装在 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);

【讨论】:

    猜你喜欢
    • 2012-05-14
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 2020-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多