安装Perf
对于Linux内核版本高于2.6.31的系统,源码里有perf,root用户可以直接在这个路径编译安装,非root用户可以拷贝出来
cp /usr/src/linux-source-3.13.0 ~ -r
cd ~/linux-source-3.13.0/tools/perf
make && make install
如果报了-Werror=implicit-fallthrough=
、-Werror=format-truncation=
之类的告警,是因为有-Werror
的编译选项。
vim ./config/Makefile
:1,$s/-Werror/-Wno-error/g
注意留意输出信息,如果缺少部分依赖,也能编译成功,但是生成的火焰图不可用,只有函数地址,没有函数名。下方的输出信息显示,缺少dwarf、gtk2、gtk2-infobar等功能。需要一一安装这些依赖。
Auto-detecting system features:
... backtrace: [ on ]
... dwarf: [ OFF ]
... fortify-source: [ on ]
... glibc: [ on ]
... gtk2: [ OFF ]
... gtk2-infobar: [ OFF ]
... libaudit: [ OFF ]
... libbfd: [ OFF ]
... libelf: [ OFF ]
... libelf-getphdrnum: [ OFF ]
... libelf-mmap: [ OFF ]
... libnuma: [ OFF ]
... libperl: [ OFF ]
... libpython: [ OFF ]
... libpython-version: [ OFF ]
... libslang: [ OFF ]
... libunwind: [ OFF ]
... on-exit: [ on ]
... stackprotector: [ on ]
... stackprotector-all: [ on ]
... timerfd: [ on ]
使用Perf捕获运行程序
perf record -F 4000 -p 31471 -g --sleep 300 #跟踪31471进程,持续300秒,每秒4000次断点,并跟踪调用栈
perf script -i perf.data > out.unfolded
安装FlameGraph
git clone git@github.com:brendangregg/FlameGraph.git
使用FlameGraph生成火焰图
cd FlameGraph
./stackcollapse-perf.pl ~/perf/out.unfolded > ~/perf/out.folded
./flamegraph.pl ~/perf/out.folded > ~/perf/out.svg
用浏览器可以打开out.svg文件。