代码接入
go
package main
import (
_ "net/http/pprof"
)
func main() {
go func() {
http.ListenAndServe("0.0.0.0:6060", nil)
}()
}
采集方式
1. CPU profiling:必须加 seconds,采样10秒
bash
# 看耗时、调用链、慢函数
curl -o cpu.pprof "http://127.0.0.1:6060/debug/pprof/profile?seconds=10"
2. 内存(堆):直接快照,不用seconds
bash
# 看哪个函数分配内存最多:内存泄漏、堆内存占用
curl -o mem.pprof "http://127.0.0.1:6060/debug/pprof/heap"
3. 协程阻塞:直接快照,不用seconds
bash
# 看协程阻塞在哪里:等待锁、等待 channel、等待 IO
curl -o block.pprof "http://127.0.0.1:6060/debug/pprof/block"
4. 锁竞争:直接快照,不用seconds
bash
# 看锁竞争: 互斥锁冲突严重的函数
curl -o mutex.pprof "http://127.0.0.1:6060/debug/pprof/mutex"
5. trace: 必须加 seconds,采样10秒
bash
curl -o trace.out "http://172.16.39.91:6060/debug/pprof/trace?seconds=10"
交互命令
- 进入命令:
bash
go tool pprof xxx.pprof
- 看概览
bash
top
top10
top20
....
- 看函数详情 + 调用链
bash
list 函数名
- 网页可视化
bash
web
weblist 函数名
- 看调用关系图
bash
tree
- 退出
bash
exit
- 例外trace
trace 不能用 go tool pprof, 必修用:
bash
go tool trace trace.out
# 或
go tool trace -http=:6061 trace.out
采集脚本
bash
#!/bin/bash
host="127.0.0.1:6060"
seconds=10
echo "开始并行采集所有 pprof,预计等待 $seconds 秒..."
# 后台并行采集
curl -o cpu.pprof "http://$host/debug/pprof/profile?seconds=$seconds" &
curl -o trace.out "http://$host/debug/pprof/trace?seconds=$seconds" &
# 瞬间采集
curl -o mem.pprof "http://$host/debug/pprof/heap"
curl -o block.pprof "http://$host/debug/pprof/block"
curl -o mutex.pprof "http://$host/debug/pprof/mutex"
# 等待后台 CPU & trace 完成
wait
echo -e "所有 5 项 pprof 采集完成!仅用时 $seconds 秒"