原理部分
- 引入 net/http/pprof 进行代码中的分析
import _ "net/http/pprof"
import "net/http"
func main() {
// 启动 pprof 服务器
go func() {
http.ListenAndServe("localhost:6060", nil)
}()
// 其他业务代码
}
这样会在 localhost:6060 启动一个 HTTP 服务器,可以在浏览器打开 http://localhost:6060/debug/pprof/ 查看各类 pprof 信息。
- 生成和查看 pprof 文件
在终端使用 go tool pprof 命令生成和查看 pprof 文件。例如:
go tool pprof http://localhost:6060/debug/pprof/heap # 查看内存使用情况
go tool pprof http://localhost:6060/debug/pprof/profile # 查看 CPU 使用情况
你还可以将这些信息保存为文件以供离线分析:
curl -o heap.prof http://localhost:6060/debug/pprof/heap
curl -o cpu.prof http://localhost:6060/debug/pprof/profile?seconds=30
go tool pprof heap.prof
go tool pprof cpu.prof
-
常见的 pprof 分析命令
进入 pprof 交互式命令行界面后,可以使用以下命令进行分析:
• top:显示 CPU 或内存消耗最多的函数,默认按消耗排序。
• list <function_name>:查看指定函数的源码以及性能消耗信息。
• web:以图形界面展示性能分析结果(需要安装 Graphviz)。
• svg:生成 SVG 格式的分析图。
• png:生成 PNG 格式的分析图。 -
分析 CPU 和内存的使用情况
在排查问题时,可以重点关注以下两方面:
• CPU Profiler:用于分析 CPU 使用情况,帮助找到耗时较长的代码段。
• Heap Profiler:用于分析内存使用情况,帮助找到内存泄漏和过高的内存使用问题。 -
常见性能瓶颈
- CPU 使用过高:检查是否有热点函数(CPU 消耗较高的函数),并尝试优化相关代码。
- 内存泄漏:关注 heap 的 top 输出中是否有内存增长,或者某些数据结构未释放。
- 阻塞操作:查看 goroutine 的 profile,检查是否存在锁竞争或通道阻塞问题。
实例演示
内存
go tool pprof http://localhost:6060/debug/pprof/heap
Fetching profile over HTTP from http://localhost:6060/debug/pprof/heap
Saved profile in /home/hope/pprof/pprof.td2_data_center_new.alloc_objects.alloc_space.inuse_objects.inuse_space.001.pb.gz
File: td2_data_center_new
Build ID: 25244974efa19a16891d82f43c0aca01f0ccd04b
Type: inuse_space
Time: Nov 13, 2024 at 3:53pm (CST)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top
Showing nodes accounting for 510.56MB,