perf profiling 分析程序性能
程序性能分析
perf 有一个功能就是按一定频率采集某一个程序的调用栈,然后对调用栈进行统计分析。如果某一个代码路径在采集结果中出现的越平凡,说明程序消耗在这个代码路径上的时间也就越多。这样我们就能很快找到程序调用最频繁的代码路径。
perf命令
perf record -F 99 -p $(pidof test1) -g -- sleep 300 这个命令是采集test1程序相关的调用栈,采样频率为99Hz,-g表示将调用栈打印出来,-- sleep 30表示采样时间是300秒
perf report -g --stdio 这个命令是查看采用的结果
例子分析
为了了解这个工具有什么样的作用,我特意写了一个程序来进行分析。
#include
int functiona(void)
{
int c = 0;
int count = 0;
for(c = 1; c < 20000; c++)
{
count++;
}
return;
}
int functionb(void)
{
int c = 0;
int count = 0;
for(c = 1; c < 40000; c++)
{
count++;
}
return;
}
int main(int argc, char * argv[])
{
for(;;)
{
functiona();
printf("call function a\n");
functionb();
printf("call function b\n");
}
return;
}
通过编译命令gcc -g -o test1 test1.c
测试过程
- test1 > /de v/null &
- perf record -F 99 -p $(pidof test1) -g -- sleep 300
- perf script > out.perf
- ./stackcollapse-perf.pl out.perf > out.folded
- ./flamegraph.pl out.folded > out.svg
测试结果分析
