

新闻资讯
技术学院Go 自带 pprof 和 testing.B 是轻量高效性能分析工具;pprof 通过 HTTP 接口采集 CPU、内存等运行时数据,testing.B 支持基准测试与并发压测,配合火焰图和对比分析可精准定位性能瓶颈与内存泄漏。
Go 自带的 pprof 和 testing.B(benchmark)是轻量、高效、无需第三方依赖的性能分析利器。它们不需额外安装工具,只要 Go 环境就绪,就能直接使用。
pprof 支持 HTTP 接口采集 CPU、内存、goroutine、block、mutex 等数据。只需在程序中导入 net/http/pprof,它会自动注册路由:
:6060):
行采集数据,例如:Go 的 testing 包原生支持 benchmark,写法简洁,结果可比性强:
xxx_test.go 文件,函数名以 Benchmark 开头,参数为 *testing.B
B.ResetTimer() 前完成初始化(如构建数据),避免计入耗时B.RunParallel 测试并发场景,或 B.N 控制循环次数-benchmem 显示内存分配统计,-count 多次运行取平均采集到的 profile 文件(如 cpu.pprof)可用交互式命令行或 Web 界面深入分析:
inuse_space(当前占用)、alloc_space(总分配量),区分“用了多少”和“申请了多少”实际排查中,几个组合操作很实用:
curl 'http://localhost:6060/debug/pprof/heap?debug=1' 记下 allocs/inuse;go tool pprof -base base.heap new.heap 对比差异runtime.GC() 强制触发 GC 后再采 heap,排除未回收对象干扰defer trace.StartRegion(ctx, "FuncName").End()(需 golang.org/x/exp/trace),配合 go tool trace 查看 Goroutine 执行流