常用工具-Perf简介

Linux性能调试工具

简介

perf是Linux 2.6+内核中的一个工具,在内核源码包中的位置 tools/perf。

perf利用Linux的trace特性,可以用于实时跟踪,统计event计数(perf stat);或者使用采样(perf record),报告(perf report|script|annotate)的使用方式进行诊断。

perf命令行接口并不能利用所有的Linux trace特性,有些trace需要通过ftrace接口得到。

参考perf-tools

安装

Ubuntu20.04直接安装

1
apt-get install linux-tools-$(uname -r) linux-tools-generic

使用

运行程序后获取pid

1
perf record -a -g -v -p <PID> sleep 30

等待30秒后会得到perf.data原始记录文件,直接查看

1
perf report -g --tui

生成火焰图perf-main.svg

1
2
3
4
git clone https://github.com/brendangregg/FlameGraph
mv perf.data FlameGraph/
cd FlameGraph
perf script | ./stackcollapse-perf.pl | ./flamegraph.pl > perf-main.svg

perf-main.svg需要使用浏览器打开,即可方便查看

生成热力图类似

1
2
3
4
5
git clone https://github.com/brendangregg/HeatMap      # or download it from github
mv perf.data HeatMap/
cd HeatMap
perf script | awk '{ gsub(/:/, "") } $5 ~ /issue/ { ts[$6, $10] = $4 } $5 ~ /complete/ { if (l = ts[$6, $9]) { printf "%.f %.f\n", $4 * 1000000, ($4 - l) * 1000000; ts[$6, $10] = 0 } }' > out.lat_us
./trace2heatmap.pl --unitstime=us --unitslat=us --maxlat=50000 out.lat_us > out.svg