Go 性能剖析实战:用 pprof 定位 CPU 与内存热点
test12026-09-212 次阅读
为什么需要 pprof
上线后接口变慢、内存缓慢上涨,靠猜往往南辕北辙。Go 标准库内置的 net/http/pprof 能在不重启服务的情况下,按需采集 CPU、堆内存、goroutine 等剖析数据,再用 go tool pprof 离线分析,直接看到是哪一行的函数吃掉了时间或内存。
接入 pprof
只需导入匿名包并起一个独立的 debug 端口,业务端口不暴露调试接口,避免安全风险。
package main
import (
"log"
"net/http"
_ "net/http/pprof"
)
func main() {
go func() {
// 仅监听本地,不对外网开放
log.Println(http.ListenAndServe("127.0.0.1:6060", nil))
}()
// 这里写你的业务 http 服务
}
采集 CPU 火焰图
采集 30 秒 CPU 样本,进入交互式命令行后可用 top 看耗时函数、用 png 生成火焰图、用 web 在浏览器打开调用图。
go tool pprof http://127.0.0.1:6060/debug/pprof/profile?seconds=30
# (pprof) top
# (pprof) png > cpu.png
# (pprof) web
排查内存与 goroutine 泄漏
内存问题看 heap,goroutine 暴涨看 goroutine。两者都支持同样的 top/web 操作。
go tool pprof http://127.0.0.1:6060/debug/pprof/heap
go tool pprof http://127.0.0.1:6060/debug/pprof/goroutine
工程建议
- debug 端口只绑 127.0.0.1,或通过跳板机访问,绝不对公网暴露。
- CPU 采集有采样开销,生产环境采样时间控制在 30 秒以内,避免影响线上。
- 内存 pprof 默认是采样的,要看精确分配用 alloc_space 视图。
- 发现 goroutine 数量只增不减,优先检查 channel 是否没有人接收、context 是否被正确取消。
T
test1
文章作者
为什么需要 pprof 上线后接口变慢、内存缓慢上涨,靠猜往往南辕北辙。Go 标准库内置的 net/http/ppro...
- 分类
- 技术
- 发布时间
- 2026-09-21
- 字数
- 约 960 字
- 阅读
- 2 次
