Go pprof:性能分析与优化
学习使用pprof工具对Go程序进行CPU、内存、goroutine等性能分析,找出瓶颈。 · 难度:入门 · +15XP
pprof简介
pprof是Go内置的性能分析工具,可以收集CPU、内存、阻塞、goroutine等运行时数据。通过net/http/pprof或runtime/pprof集成。
HTTP方式
import _ "net/http/pprof"
func main() {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
// 程序逻辑...
}
命令行分析
# 收集CPU profile
curl -o cpu.prof http://localhost:6060/debug/pprof/profile?seconds=30
# 交互式分析
go tool pprof cpu.prof
(pprof) top10
(pprof) web
| 端点 | 说明 |
|---|---|
| /debug/pprof/ | 概览 |
| /debug/pprof/profile | CPU分析 |
| /debug/pprof/heap | 堆内存 |
| /debug/pprof/goroutine | goroutine栈 |
可视化
使用go tool pprof -http=:8080 cpu.prof启动Web界面,查看火焰图和调用图。
练习提示
在代码中添加pprof端点,访问localhost:6060/debug/pprof/heap?debug=1查看内存分配。尝试优化代码中的内存分配。