- 引入相关包:
在代码中引入
net/http
和runtime/pprof
包。例如:
import (
"net/http"
_ "net/http/pprof"
)
- 启动HTTP服务:
在
main
函数中启动一个HTTP服务来暴露pprof
数据。
func main() {
go func() {
http.ListenAndServe(":6060", nil)
}()
// 主程序逻辑
}
- 获取性能数据:
通过浏览器或工具访问
http://localhost:6060/debug/pprof/
,该页面会展示各种性能分析数据的链接,如:
- CPU分析:访问
http://localhost:6060/debug/pprof/profile
,可获取CPU性能分析数据,一般通过go tool pprof
工具来分析,例如go tool pprof http://localhost:6060/debug/pprof/profile
。
- 内存分析:访问
http://localhost:6060/debug/pprof/heap
,同样使用go tool pprof
分析,如go tool pprof http://localhost:6060/debug/pprof/heap
。
- 其他分析:还有
goroutine
分析(http://localhost:6060/debug/pprof/goroutine
)、block
分析(http://localhost:6060/debug/pprof/block
)等,也用go tool pprof
进行深入分析。