Supposing I have a function (a decorator) that measures the duration of given function:
#include <unistd.h>
void measure(void (*f)()) {
time_t tBegin = time(NULL);
f();
time_t tEnd = time(NULL);
cout << "Duration: " << (tEnd - tBegin) << " sec" << endl;
}
And I want to measure the duration of a method of a class. For example:
class Myclass {
private:
double _d;
public:
Myclass(double d) : _d(d) {}
void run() {
measure(m);
}
void m() const {
usleep(1000000 * _d);
}
};
int main() {
Myclass obj(2.0);
obj.run();
return 0;
}
Such implementation leads to the error:
error: invalid use of non-static member function
Is there a way in C++ to implement it correctly? It's supposed not to modify the external function measure
and the measured method is exactly non-static (it uses data of the instance). The measurement should be inside of the method run
.
I need solution for C++ 1998/2003 Standard.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…