在执行时间方面对现有代码进行概要分析时,我需要一些帮助。目的是加快速度。
我已经得到一些以前处理过的代码。它完全是用OO概念用C++编写的。有一个基于GUI的界面,选择某个选项将运行选定的代码段。 (该项目大约有11个类(class))。
我希望能够按下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
这样,我知道哪个类(class)花费最多的时间,然后知道哪个类(class)需要改进。但是,我不知道如何去做。我只有基本的C++知识。
我确实读了这篇文章:find c++ execution time,但是由于程序不是串行的。一个类调用另一个,而另一个调用,我不知道如何实现系统时钟/滴答声?
我读过类似Valgrind,Zoom,Poor Man's Profiler等的程序,但老实说,我不知道如何将其与代码集成。有没有这么简单的方法?
我也读过这种方法:How can I profile C++ code running in Linux?,但是我看不到如何获得有关基于类的信息(第1类,第2类等)的精确信息。
有人可以建议新手吗?
最佳答案
Valgrind(子工具callgrind)非常易于使用。您只需要确保将足够的调试信息编译/链接到程序中,以便callgrind可以找到要调用的各种函数的名称。然后,与其直接调用程序,不如将其(及其参数)作为参数传递给valgrind,例如:
valgrind --tool=callgrind --trace-children=yes <myprogram> <myprogram_args>
(--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();
}
关于c++ - 根据执行时间对C++项目进行性能分析,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11006658/