在根据执行时间分析现有代码方面,我需要一些帮助.目的是加快速度.
我已经获得了一些以前工作过的代码.它完全用C++编写,带有OO概念.有一个基于GUI的界面,选择一个选项运行选定的代码.(作为项目的一部分,大约有11个班级).
我希望能够按下GUI选项并让代码运行并生成资源映射,如:
Functions of Class 1 = 20% of execution time
Functions of Class 2 = 60% of execution time
Functions of Class 3 = 10% of execution time
Functions of Class 4 = 10% of execution time
Run Code Online (Sandbox Code Playgroud)
这样,我知道哪个班级占用的时间最多,然后知道哪个班级可以继续工作并改进.但是,我不知道该怎么做.我只有基本的C++知识.
我读过这篇文章:找到c ++执行时间,但是因为程序不是串行的.一个类调用另一个,调用另一个,我不知道系统时钟/滴答是如何实现的?
我读过Valgrind,Zoom,Poor Man's Profiler等程序,但实际上并不知道如何将它与代码集成.有这么简单的方法吗?
我也读过这个方法:如何分析在Linux中运行的C++代码?但是,我不知道如何获得关于基于类的信息的尖锐信息(Class 1,Class 2等)
有人可以建议新手吗?
Sco*_*ett 17
Valgrind(subtool callgrind)使用非常简单.您只需要确保将足够的调试信息编译/链接到您的程序中,以便callgrind可以找到被调用的各种函数的名称.然后,不是直接调用程序,而是将它(及其参数)作为参数传递给valgrind,如:
valgrind --tool=callgrind --trace-children=yes <myprogram> <myprogram_args>
Run Code Online (Sandbox Code Playgroud)
(如果您的真实可执行文件隐藏在某些层或包装层脚本层之后,则存在--trace-children)
请注意,您的程序运行速度会慢得多(比较慢100倍),因为每个函数入口点都在跟踪.
存在各种工具来探索callgrind的输出,特别是kcachegrind/qcachegrid.
或者,您可以测量少数高级函数的系统时钟周期(因此您可以看到"函数X及其下面的所有内容所花费的时间"),并在找到热点时向下查看代码.
像这样的东西(从概念上讲,需要正确组织成标题/来源):
struct FunctionTimer {
FunctionTimer(char const * name) : mName(name), mStartTime(clock()) { }
~FunctionTimer() { mFunctionTimes[mName] += clock() - mStartTime; }
static void report()
{
... iterate through mFunctionTimes, printing out
the names and accumulated ticks ...
}
std::string mName;
clock_t mStartTime;
static std::map<std::string, clock_t> mFunctionTimes;
};
...
void myfunc()
{
FunctionTimer ft("myfunc");
... code of myfunc ...
}
...
int main(int argc, char* argv[])
{
... do stuff ...
FunctionTimer::report();
}
Run Code Online (Sandbox Code Playgroud)