perf+gprof+gprof2dot+graphviz進行效能分析熱點
perf分析熱點程式碼
perf是linux的一款效能分析工具
perf list ;;列出平臺中perf支援的事件命令
sudo perf timechart record python conv2d.py ;;各種統計資訊圖形化
sudo perf timechart ;;再執行,就會產生csv圖形檔案
perf record -e cpu-clock ./test ;;結合report命令找出熱點函式
perf record -F 50000 -e cpu-clock ./test ;;指定頻率
perf stat -r 10 ./test ;;執行10次求均值
perf record -g -e cpu-clock ./test ;;呼叫關係顯示
perf report ;;可多次
perf stat ./test ;;顯示程式的cpu、預取、cache miss等
perf record -e cpu-clock python cnn.py ;;使用python執行卷積神經網路cnn.py
perf report ;;顯示出來,回車再回車
作圖顯示熱點圖
請確保系統安裝python、gprof2dot、graphviz軟體包
Ubuntu:
$sudo apt-get install python graphviz
$sudo pip install gprof2dot
centos/redhat/fedora:
$yum install python graphviz gprof2dot
以程式test.c為例進行演示
1.建立C檔案 test.c
void longa()
{
int i,j;
for(i = 0; i < 1000000; i++)//迴圈1百萬次
j=i;
}
void foo2()
{
int i;
for(i=0 ; i < 10; i++)
longa();
}
void foo1()
{
int i;
for(i = 0; i< 100; i++)
longa();
}
int main(void)
{
foo1();
foo2();
}
2. 終端執行命令, -pg引數產生供gprof剖析用的可執行檔案(會在每個function call 插入一個_mcount的routine 功能) -g引數產生供gdb除錯用的可執行檔案。更多GCC引數可見這篇部落格http://blog.chinaunix.net/uid-21411227-id-1826747.html
$ gcc -pg -g -o test test.c
3.接著執行 ./test ,會在當前目錄下預設生成 gmon.out
$./test
4.執行以下命令,生成圖片output.png
$ gprof ./test | gprof2dot -n0 -e0 | dot -Tpng -o output.png
檢視圖片,效果圖如下:可以看到函式呼叫的百分比和次數,以及熱點線路
對於Python程式,若想要構圖可以使用以下方法,需要安裝graphviz,根據情況修改gprof2dot.py路徑,以Ubuntu為列:
$sudo apt-get install graphviz
$python -m cProfile -o output.pstats simple_conv2d.py
$python /usr/local/lib/python2.7/dist-packages/gprof2dot.py -f pstats output.pstats | dot -Tpng -o profiling_results.png
參考文獻
http://www.tuicool.com/articles/UrQvqa
http://www.51testing.com/html/97/13997-79952.html