Perf工具学习笔记
1.WSL上Perf安装
- (1) 设置内核版本变量
KERNEL_VERSION
>> export KERNEL_VERSION=$(uname -r | cut -d'-' -f1)
- (2) 下载内核源码
>> git clone --depth 1 --single-branch \
--branch=linux-msft-wsl-${KERNEL_VERSION} \
https://github.com/microsoft/WSL2-Linux-Kernel.git
- (3) 编译安装
# 1.安装依赖库
>> sudo apt-get install flex bison dwarves binutils-dev libdw-dev libnewt-dev python3-dev libperl-dev libzstd-dev libunwind-dev
# 2.进入工程目录
>> cd WSL2-Linux-Kernel
# 3.make源码编译
>> make KCONFIG_CONFIG=Microsoft/config-wsl -j 8
# 4.编译perf
>> cd tools/perf && make -j 8
# 5.添加环境变量
>> vim ~/.zshrc
export PERF_TOOL=/home/mirror/software/WSL2-Linux-Kernel/tools/perf
export PATH=$PATH:$PERF_TOOL
>> source ~/.zshrc
# 6.查看版本
>> perf --version
perf version 5.15.167.4.g6ac7abbd97a0
2.FlameGraph工具安装
# 1.下载工具
>> git clone git@github.com:brendangregg/FlameGraph.git
# 2.获取工具路径
>> cd FlameGraph && pwd
/home/mirror/software/FlameGraph
# 3.添加系统环境变量
>> vim ~/.zshrc
export FLAME_GRAPH=/home/mirror/software/FlameGraph
export PATH=$PATH:$FLAME_GRAPH
>> source ~/.zshrc
3.性能测试命令
简单测试代码:
/*
* @Author: chenjingyu
* @Date: 2025-01-03 17:44:22
* @Contact: 2458006466@qq.com
* @Description: main
*/
#include <iostream>
#include <unistd.h>
#include <string>
void long_test() {
int i, j;
for (i = 0; i < 10000000; ++i) {
j = i;
}
}
void foo2() {
int i;
for (i = 0; i < 1000; ++i) {
long_test();
}
}
void foo1() {
int i;
for (i = 0; i < 1000; ++i) {
long_test();
}
}
int main(int argc, char *argv[]) {
foo1();
foo2();
return 0;
}
编译测试:
# 1.编译
>> g++ -o main main.cc
# 2.对一个正在运行的进行进行采样
>> perf record -p PID -g -- sleep 60
# 3.全新运行一个二进制文件main,进行采样
>> perf record -F 99 -g ./main -- sleep 60
# 4.生成火焰图
>> perf script -i perf.data &> perf.unfold
>> stackcollapse-perf.pl perf.unfold &> perf.folded
>> flamegraph.pl perf.folded > perf.svg
使用浏览器打开perf.svg即可查看结果。