想象一下有一个类,其中包含一些成员函数。
class Test
{
public:
Test();
virtual ~Test();
int init(int arg1, double arg2);
private:
[...]
而在我的构造函数中,我调用了其中一个方法。
Test::Test()
{
[...]
int value = init(1, 1.2);
}
我该如何以简洁明了的方式测量我的方法
init(...)
的执行时间,而不会破坏我的程序?目前,我使用以下代码:
Test::Test()
{
[...]
auto start = std::chrono::high_resolution_clock::now();
int value = init(1, 1.2);
auto stop = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> duration = stop - start;
std::cout << duration.count() * 1000 << "ms\n";
}
它的功能正常,但我认为它相当混乱,我想要一个“更清晰”的解决方案。
是否有一种方法可以使用某种函数来接受成员函数和其他参数,例如:
int value = countTime(function, arg1, arg2);
我不知道是否可以将function()
的返回值传递到countTime()
中,以便不会打断我的代码工作流程。
编辑: 这是我的TimeMeasure类
namespace tools
{
class TimeMeasure
{
public:
TimeMeasure()
{
m_start = std::chrono::high_resolution_clock::now();
}
virtual ~TimeMeasure()
{
m_stop = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> duration = m_stop - m_start;
std::cout << duration.count() << "ms\n";
}
public:
typedef std::chrono::time_point<std::chrono::high_resolution_clock> HighResClock;
private:
HighResClock m_start;
HighResClock m_stop;
};
template <typename T, typename F, typename... Args>
auto measure(T *t, F &&fn, Args... args)
{
tools::TimeMeasure timeMeasure;
return (t->*fn)(std::forward<Args>(args)...);
}
}
在我的构造函数Test()
中,我这样使用函数measure
Test()
{
[...]
tools::measure(this, Test::init, filepath);
}
int init(const std::string& filepath) const
需要一个文件路径的字符串。在我的情况下只有一个参数。
不幸的是,我得到了一个invalid use of non-static member function 'int init(const string&) const'
错误。
我想知道构造函数是否不是成员函数。那么为什么会出现这个错误?
编辑2:
根据OznOg的答案,我只是忘记了提交指向我的函数的指针。
所以这将是正确的函数调用。
tools::measure(this, &Test::init, filepath);
stop - start
赋值给std::chrono::duration<double, std::milli>
,并且去掉* 1000
。让<chrono>
帮你完成这些转换。如果你养成了这个习惯,在处理复杂的事情时,你会减少编码错误。 - Howard Hinnantgprof
似乎会产生相对较大的开销。 - linux_lover