生成可视化的图形
生成可视化的图形需要下载gprof2dot:gprof2dot · PyPI
这是个Python脚本,下载之后解压,确认gprof2dot.py有运行权限 ,并把这个脚本添加到$PATH路径中的任一文件夹下,我是在/usr/bin目录下创建了它的软连接,这样就可以直接在终端下执行gprof2dot.py了。
xulei@xulei-PC:~/Downloads$ tar -xvzf gprof2dot-2021.2.21.tar.gz
gprof2dot-2021.2.21/
gprof2dot-2021.2.21/LICENSE.txt
gprof2dot-2021.2.21/MANIFEST.in
gprof2dot-2021.2.21/PKG-INFO
gprof2dot-2021.2.21/README.md
gprof2dot-2021.2.21/gprof2dot.egg-info/
gprof2dot-2021.2.21/gprof2dot.egg-info/PKG-INFO
gprof2dot-2021.2.21/gprof2dot.egg-info/SOURCES.txt
gprof2dot-2021.2.21/gprof2dot.egg-info/dependency_links.txt
gprof2dot-2021.2.21/gprof2dot.egg-info/entry_points.txt
gprof2dot-2021.2.21/gprof2dot.egg-info/top_level.txt
gprof2dot-2021.2.21/gprof2dot.py
gprof2dot-2021.2.21/setup.cfg
gprof2dot-2021.2.21/setup.py
xulei@xulei-PC:sudo ln -s ~/Downloads/gprof2dot-2021.2.21/gprof2dot.py /usr/bin/gprof2dot.py
xulei@xulei-PC:~/Downloads$ ls -l !$
ls -l /usr/bin/gprof2dot.py
lrwxrwxrwx 1 root root 54 4月 28 18:04 /usr/bin/gprof2dot.py -> /home/xulei/Downloads/gprof2dot-2021.2.21/gprof2dot.py
gprof分析性能,然后可视化
gprof是GNU profile工具,可以运行于linux、AIX、Sun等操作系统进行C、C++、Pascal、Fortran程序的性能分析,用于程序的性能优化以及程序瓶颈问题的查找和解决。通过分析应用程序运行时产生的“flat profile”,可以得到每个函数的调用次数,每个函数消耗的处理器时间,也可以得到函数的“调用关系图”,包括函数调用的层次关系,每个函数调用花费了多少时间。
gprof会精确的给出函数被调用的时间和次数,给出函数调用关系
步骤如下:
1 g++ -pg -o test test.cpp
使用-pg参数
编译器会自动在目标代码中插入用于性能测试的代码片断,这些代码在程序运行时采集并记录函数的调用关系和调用次数,并记录函数自身执行时间和被调用函数的执行时间。
2 运行程序./test
运行程序的时间会稍慢于正常编译的可执行程序的运行时间。程序运行结束后,会在程序所在路径下生成一个缺省文件名为gmon.out的文件,这个文件就是记录程序运行的性能、调用关系、调用次数等信息的数据文件。(这个文件gprof在分析程序时需要)
3 gprof ./test | gprof2dot.py |dot -Tpng -o gprof_result.png
使用gprof命令来分析记录程序运行信息的gmon.out文件,如:gprof test gmon.out则可以在显示器上看到函数调用相关的统计、分析信息。也可以采用
3.1 gprof ./test gmon.out> gprof_result.txt重定向到文本文件以便于后续分析。
3.2 gprof2dot.py -f prof gprof_result.txt | dot -Tpng -o gprof_result.png 产生图片
4 打开png查看结果图片
Callgrind
Callgrind收集程序运行时的一些数据,函数调用关系等信息,还可以有选择地进行cache模拟。在运行结束时,它会把分析数据写入一个文件。callgrind_annotate可以把这个文件的内容转化成可读的形式。检查代码覆盖和性能瓶颈:
我们调用valgrind的工具执行程序:
valgrind --tool=callgrind ./test
会在当前路径下生成callgrind.out.pid(当前生产的是callgrind.out.19196),如果我们想结束程序,可以:
killall callgrind
然后我们看一下结果:
callgrind_annotate --auto=yes callgrind.out.19196 > callgrind_result.txt
Callgrind的生成调用图过程:
1 gcc -g -o test test.c
2 执行 valgrind --tool=callgrind ./test,执行完成后在目录下生成"callgrind.out.pid"的文件这是分析文件
3 分析结果
3.1 可以直接利用:callgrind_annotate callgrind.out.pid 打印结果,
3.2也可以使用:gprof2dot.py -f callgrind callgrind.out.pid |dot -Tpng -o callgrind_report.png 来生成图形化结果
添加一个valgrind的massif分析分析堆问题的链接,步骤如下
1 gcc -g -o test test.c
2 valgrind --tool=massif ./test
在当前目录下会生成名字格式为massif.out.<pid>的文件。
3 massif-visualizer 打开massif.out.pid文件,可视化显示结果。
deepin系统massif-visualizer的安装 sudo apt-get install massif-visualizer 即可安装上