使用Perf工具分析程序性能

仅个人学习与记录

perf

perf是Linux内核提供的一个性能分析工具,可以跟踪程序的运行并分析其各种性能比如CPU负载、内存占用等

安装/开启perf

  1. debian
1
2
sudo apt install linux-perf
sudo apt install linux-perf-$(uname -r)
  1. ubuntu
1
sudo apt install linux-tools-$(uname -r) linux-cloud-tools-$(uname -r)
  1. CentOS/openEuler
1
sudo yum install perf

使用flamegraph输出热点图

flamegraph地址

下载安装后可配合perf输出的数据生成程序直观的热点函数图进行进一步的分析:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
benchmark() {
fileName=$1
outputName=$2
perf record -e cpu-clock -g -o ${fileName}.data ./${fileName}
perf script -i ./${fileName}.data &> ./${fileName}.unfold
stackcollapse-perf.pl ./${fileName}.unfold &> ./${fileName}.folded
flamegraph.pl ./${fileName}.folded > ./benchmarks/${fileName}.svg
mv ${fileName}.data ${fileName}.unfold ${fileName}.folded ./data
}

files=("matrix_no_optimize" "matrix_o1" "matrix_o2" "matrix_o3" "matrix_of")

for file in ${files[@]}
do
benchmark ${file} ${file}
done

一些使用问题

  1. Accesss to performance monitoring and observability operations is limited

解决方法:

1
sudo sysctl -w kernel.perf_event_paranoid=-1

常用命令

perf stat ls - 打印出程序使用硬件的情况

参考资料

  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

请我喝杯咖啡吧~

支付宝
微信