如何为每个类的方法添加计时器?

mrg*_*oom 1 c++ boost timer

如何"隐式"为每个类的方法添加某种计时器,不包括构造函数和析构函数?

我正在为每个课堂方法做什么:

void MyClass::SomeFunc()
{
    cout << __PRETTY_FUNCTION__ <<endl;

    boost::timer::cpu_timer timer;

    //Some code

    boost::timer::cpu_times elapsed = timer.elapsed();
    cout << __PRETTY_FUNCTION__ << " : WALLCLOCK TIME: " << elapsed.wall / 1e9 << " seconds" << endl;
}
Run Code Online (Sandbox Code Playgroud)

我想要的是:

void MyClass::SomeFunc()
{
    //Some code
}
Run Code Online (Sandbox Code Playgroud)

假设这两部分代码的行为应该是等效的.

Joh*_*nck 5

您几乎可以使用RAII实现此目的:

struct FunctionLogger {
    FunctionLogger(const char* func)
        : m_func(func)
    {
        cout << func <<endl;
    }
    ~FunctionLogger() {
        boost::timer::cpu_times elapsed = timer.elapsed();
        GSULOG << m_func << " : WALLCLOCK TIME: " << elapsed.wall / 1e9 << " seconds" << endl;
    }
    const char* m_func;
    boost::timer::cpu_timer timer;
};
Run Code Online (Sandbox Code Playgroud)

现在:

void MyClass::SomeFunc()
{
    FunctionLogger _(__PRETTY_FUNCTION__);
    //Some code
}
Run Code Online (Sandbox Code Playgroud)

当然,如果你喜欢宏:

#define FL FunctionLogger _(__PRETTY_FUNCTION__)

void MyClass::SomeFunc()
{
    FL;
    //Some code
}
Run Code Online (Sandbox Code Playgroud)

如果您正在寻找这种工业级解决方案,那么术语是面向方面编程.但它不是C++直接支持的.