callgrind
是valgrind
工具套件中用於分析程序性能的一個工具,它能夠得到粒度爲函數、代碼行和指令級別的性能數據,具體來說,我們可以得到某個函數、某行代碼、某條指令處累計執行了多少條指令。
我們看一個實例:
// foo.cpp
int accumulate(int begin, int end)
{
int result = 0;
for (int i = begin; i < end; i++)
{
result += i;
}
}
int accumulate0_100000()
{
return accumulate(0, 100000);
}
int accumulate0_200000()
{
return accumulate(0, 200000);
}
int main()
{
accumulate0_100000();
accumulate0_200000();
return 0;
}
accumulate
用來從begin
累加到end
,這個函數很蠢,蠢到一開O2編譯器都忍不住幫你優化掉(所以編譯時不要開優化),但這並不影響拿它來展示callgrind
的使用。
編譯:
g++ -g ./foo.cpp -o foo #別開優化
callgrind
分析:
valgrind --tool=callgrind --dump-instr=yes ./foo
輸出爲:
==31526== Callgrind, a call-graph generating cache profiler
==31526== Copyright (C) 2002-2017, and GNU GPL'd, by Josef Weidendorfer et al.
==31526== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==31526== Command: ./foo
==31526==
==31526== For interactive control, run 'callgrind_control -h'.
==31526==
==31526== Events : Ir
==31526== Collected : 2226406
==31526==
==31526== I refs: 2,226,406
其含義是程序共執行了2226406條指令。
kcachegrind
可視化結果:
kcachegrind
其結果爲:
這些百分值都代表當前函數中執行過的指令數佔程序執行過的指令數的百分比。可以將其切換成絕對值:
我們可以發現main
中的指令數並不等於下面兩個子函數中指令數只和,這是因爲有些指令(例如callq
)是直接在main
函數中執行的。
還可以查看某行代碼中累計執行過多少條指令:
以及某條指令處累計執行過多少條指令:
可以看出來cmp
指令累計被執行了300002次。
更多用法和參數請查看手冊。