【发布时间】:2018-10-20 12:58:32
【问题描述】:
我想优化我的应用程序,尤其是某些功能的执行速度。
想象有一个类有一些成员函数
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>为您进行这些转换。如果您养成这样做的习惯,当事情变得真正复杂时,您的编码错误就会减少。 -
@HowardHinnant 感谢您的建议!我不知道这个
-
@LightnessRacesinOrbit 我已经发现了这个工具。不幸的是,这对我的需求来说有点太多了。我只想测量某些功能。此外,
gprof似乎产生了比较大的开销。 -
这不是“太多”,它正是分析函数执行的合适工具,而不是通过容易出现各种错误的应用程序进行时间测量。当然,它会减慢您的程序速度,因此您不会获得绝对速度,但无论如何绝对速度是无用的(您的程序将在多台 PC 上运行,对吗?) - 您需要知道当前哪个功能比所有其他功能,为此它很到位。