Go语言pprof性能分析指南
在 Go 语言中,pprof
是强大的性能分析工具,用于诊断程序中的性能问题(如 CPU 占用、内存泄漏、Goroutine 泄露等)。以下是详细的使用步骤:
1. 启用 pprof 服务
在代码中导入 net/http/pprof
包,它会自动注册 pprof 路由到默认 HTTP 多路复用器:
package mainimport ("net/http"_ "net/http/pprof" // 自动注册路由
)func main() {// 启动 HTTP 服务(通常在独立 Goroutine 中运行)go func() {http.ListenAndServe("localhost:6060", nil) // 默认地址}()// ... 你的业务逻辑 ...
}
2. 收集性能数据
程序运行后,通过以下方式获取分析数据:
CPU 分析
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
-
seconds=30
表示采样 30 秒的 CPU 使用情况。