Go 自带 profiling 工具轻量高效,支持 CPU、内存、goroutine 等多种分析:CPU profile 定位计算瓶颈,memory profile 区分 allocs/heap 识别分配热点与泄漏,goroutine/block profile 发现协程堆积与锁竞争,结合 pprof 可视化快速下钻定位。
Go 自带的 profiling 工具非常轻量、高效,无需第三方依赖,只要几行代码就能开启 CPU、内存、goroutine 等多种性能数据采集。关键在于:启动时启用 profile endpoint 或写入文件,再用 go tool pprof 分析,就能快速定位热点函数和资源消耗大户。
CPU profile 记录的是程序在一段时间内哪些函数实际占用了 CPU 时间。它不是采样“谁在运行”,而是采样“谁在执行指令”。适合排查响应慢、计算密集型瓶颈。
import _ "net/http/pprof",然后访问 http://localhost:6060/debug/pprof/profile?seconds=30(默认采样 30 秒)go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
top10 查看耗时 Top 10 函数;web 生成调用图(需安装 graphviz);list 函数名 查看具体源码行耗时分布内存 profile 分为两种:allocs(累计分配总量)和 heap(当前堆上存活对象)。排查高频小对象分配(如字符串拼接、结构体反复 new)或长期未释放的大对象,优先看 heap。
curl -o mem.pprof http://localhost:6060/debug/pprof/heap
go tool pprof http://localhost:6060/debug/pprof/allocs
curl .../heap 得 baseline,压测后再抓一次,用 pprof -base baseline.pprof after.pprof 查增长项当服务并发升高后响应变慢、goroutine 数持续上涨,或接口延迟抖动明显,应检查 goroutine 和 block profile。
/debug/pprof/goroutine?debug=1 显示所有 goroutine 当前调用栈(含阻塞位置),适合查死循环、忘记 close channel、未结束的 time.Sleep/debug/pprof/block 记录因同步原语(mutex、channel send/recv)而阻塞的 goroutine,能暴露
锁竞争、channel 缓冲不足、无缓冲 channel 同步等待等问题go tool pprof -http=:8080 http://localhost:6060/debug/pprof/block 可视化阻塞调用链别等线上出问题才分析。本地复现 + 快速 profile 是最高效的路径:
go run -gcflags="-m" main.go 看编译器是否做了逃逸分析,提前发现隐式堆分配go tool pprof -http=:8081 cpu.pprof heap.pprof,pprof 会自动关联时间线