首先,使用-pg -g选项编译程序;然后运行文件,生成gmon.out文件; 使用gprof命令运行程序,得到prof.log文件;使用gprof2dot.py程序对prof.log文件进行处理,得到dot文件,其中参数-n0.5表示低于0.5%的函数不显示,-s表示简化函数名;然后可以通过xdot查看,也可以使用dot命令将其转换为图片。
程序得到的性能分析图片如下:

使用valgrind进行性能分析,过程如下:
***@Ubuntu:~/Performance$ valgrind --tool=callgrind ./mt
==7389== Callgrind, a call-graph generating cache profiler
==7389== Copyright (C) 2002-2012, and GNU GPL'd, by Josef Weidendorfer et al.
==7389== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==7389== Command: ./mt
==7389==
==7389== For interactive control, run 'callgrind_control -h'.
==7389==
==7389== Events : Ir
==7389== Collected : 231867136
==7389==
==7389== I refs: 231,867,136
Profiling timer expired
***@ubuntu:~/Performance$ ls
callgrind.out.7389 gmon.out gprof2dot.py gprof.dot gprof.png map_test.cpp mt prof.log
***@ubuntu:~/Performance$ Python gprof2dot.py -f callgrind -n10 -s callgrind.out.7389 > valgrind.dot
***@ubuntu:~/Performance$ xdot valgrind.dot
***@ubuntu:~/Performance$ dot -Tpng valgrind.dot -o valgrind.png
首先,使用valgrind运行程序,会生成callgrind.out.7389,其中7389是运行程序的进程号,值得一提的是,valgrind还可以做其他很多事情,比如内存泄漏的检测等。
其次,使用gprof2dot.py生成dot文件。
性能分析结果如下图:

由图可见,valgrind的性能分析比gprof要详尽的多。
C++程序的性能分析到此就介绍完了,有不详尽之处,请多多指教。
