性能分析工具
Table of Contents
1. 简介
linux下有几个工具可以用于做性能分析:
1 Gperftools CPU Profiler
2 Callgrind
3 Perf
2. Gperf
2.1. 编译
在编译参数里加入-lprofiler,编译代码
2.2. 环境变量
通过环境变量来设置分析文件输出目录
export CPUPROFILE=/tmp/cpu_gateway.prof
2.3. 启动进程
进程正常 启动、停止后,会在$CPUPROFILE指定的位置中生成一份gperf格式的分析数据
2.4. 转换数据格式
通过如下鸣喇叭gperf格式的数据转成dot格式
pprof -dot EXEgateway_debug /tmp/cpu_gateway.prof > /tmp/cpu_gateway.dot
2.5. 生成图表
可以生成pdf或者png格式
dot -Tpng /tmp/cpu_gateway.dot -o /tmp/cpu_gateway.png
dot -Tpdf /tmp/cpu_gateway.dot -o /tmp/cpu_gateway.pdf
3. Callgrind
3.1. 收集性能数据
和gprof不同,它不需要在编译代码时添加额外参数,只需要在启动进程时前面加上callgrind参数
valgrind --tool=callgrind --callgrind-out-file=/tmp/callgrind_gateway.out EXEgateway_debug
如果需要每个线程生成单独的分析文件,则需要增加参数:
--separate-threads=yes
3.2. 转换数据格式
把上面产生的数据文件转换成dot格式的数据:
python gprof2dot.py -f callgrind -n10 -s /tmp/callgrind_gateway.out > /tmp/callgrind_gateway.dot
3.3. 生成图表
跟上面的生成图表类似,可以用以下命令生成pdf或者png格式
dot -Tpng /tmp/cpu_gateway.dot -o /tmp/cpu_gateway.png
dot -Tpdf /tmp/cpu_gateway.dot -o /tmp/cpu_gateway.pdf
4. perf线上收集
比callgrind更方便的是perf,它可以直接在线上收集性能数据,在任何时候收集正在运行中的进程数据而不需要重启进程
perf record -g -o /tmp/perf_wd03_ags_s11_gw.data EXEgameworld_debug # 带着参数启动进程(一般不用)
perf record -o /tmp/perf_wd03_ags_s11_gw.data -p 29358 --call-graph dwarf # 直接指定进程ID收集
4.1. 查看分析数据
当收集完毕后(一般是主动Ctrl+C时),可以用以下命令交互式查看分析图
perf report -i /tmp/perf_wd03_ags_s11_gw.data
如果想生成纯文本格式的分析图,可以执行以下命令:
perf report -i perf_wd03_ags_s11_gw.data --stdio --sort cpu > perf_wd03_ags_s11_gw.cpu.txt
如果只想查看当前函数开销而忽略子函数,可以使用–no-children或-n选项。
4.2. 火焰图
如果觉得上面的分析图不够好看,可以生成火焰图
首先使用 perf script 将收集到的数据转换为更易于处理的格式
perf script -i /tmp/perf_wd03_ags_s11_gw.data > perf_${file_name}.perf
然后使用FlameGraph工具生成火焰图
./stackcollapse-perf.pl < ./perf_${file_name}.perf | ./flamegraph.pl > perf_gameworld.svg
可以通过git命令检出FlameGraph代码:
git clone https://github.com/brendangregg/FlameGraph
cd FlameGraph
4.3. 懒人一键脚本
以下附上一份快捷脚本,方便自动监听&分析&生成文本+火焰图:
#!/bin/bash
pid=$1
file_name=$2
timeout=$3
# 检查pid跟file_name合法性
if [ -z $pid ] || [ -z $file_name ]; then
echo "Usage: pid file_name [timeout_s]"
exit 1
fi
# 没设置超时秒数,则默认10秒
if [ -z $timeout ] ; then
timeout=10
fi
echo "Start perf collection ....."
timeout ${timeout} perf record -o /tmp/perf_${file_name}.data -p ${pid} --call-graph dwarf
echo "Generating txt file ....."
perf report -i /tmp/perf_${file_name}.data --stdio --sort cpu > /tmp/perf_${file_name}.cpu.txt
echo "Generation svg fild ....."
perf script -i /tmp/perf_${file_name}.data > /tmp/perf_${file_name}.perf
./stackcollapse-perf.pl < /tmp/perf_${file_name}.perf | ./flamegraph.pl > /tmp/perf_${file_name}.svg
echo "======= see those files ======="
echo "/tmp/perf_${file_name}.cpu.txt"
echo "/tmp/perf_${file_name}.svg"
echo "======= Generation done ======="
5. Valgrind内存分析
需要让可执行文件中valgrind的修饰下启动:
valgrind --tool=massif ./EXExxx
ms_print massif.out.[PID] > analysis.txt
analysis.txt就是内存占用分析结果