文章目录
- go tool pprof http://localhost:6060/debug/pprof/profile 交互模式下可用命令: top # 查看最耗 CPU 函数 list Foo # 查看某个函数的源码热区 web # 生成火焰图 (需安装 Graphviz) 也可以保存为文件再分析: go tool pprof -svg http://localhost:6060/debug/pprof/profile > cpu.svg
- go tool pprof http://localhost:6060/debug/pprof/heap 默认是采样对象分配,想查看实际内存使用,加上参数: runtime.MemProfileRate = 1 // 设置为 1 会记录所有内存分配
目录
- 一、pprof 能做什么?
- 二、快速上手:集成 pprof 到项目
- 三、使用go tool pprof进行分析
- 1. CPU 分析示例
- 2. 内存分析示例
- 四、可视化工具推荐
- 五、调试技巧总结
- 1. 分析 goroutine 泄露
- 2. 获取完整 trace
- 3. 阻塞分析(lock、channel阻塞)
- 六、常见场景与建议
- 七、部署环境建议
- 八、总结命令备查
Go 标准库自带的 net/http/pprof 包可用于 CPU、内存、阻塞、goroutine 等多个维度的性能分析。结合 go tool pprof、浏览器、图形化工具能直观发现问题。
| 类型 | 分析内容 |
|---|---|
| CPU Profiling | 程序中最耗 CPU 的函数与代码路径 |
| Memory Profiling | 分析对象分配与内存使用情况 |
| Block Profiling | 查看阻塞(如锁、channel)的热点位置 |
| Goroutine Dump | 分析 goroutine 状态与泄漏问题 |
| Trace | 精细化查看事件流程与调度(更底层更耗资源) |
在你的 HTTP 项目中引入:
import _ "net/http/pprof"
import "net/http"
func main() {
go func() {
http.ListenAndServe("localhost:6060", nil)
}()
// 其他逻辑
}
然后运行项目,访问:
http://localhost:6060/debug/pprof/
常见路径:
/debug/pprof/:导航页/debug/pprof/goroutine:Goroutine 分析/debug/pprof/heap:内存分析/debug/pprof/profile:CPU 分析(默认 30 秒)/debug/pprof/block:阻塞分析/debug/pprof/threadcreate:线程创建分析
go tool pprof http://localhost:6060/debug/pprof/profile
交互模式下可用命令:
top # 查看最耗 CPU 函数 list Foo # 查看某个函数的源码热区 web # 生成火焰图 (需安装 Graphviz)
也可以保存为文件再分析:
go tool pprof -svg http://localhost:6060/debug/pprof/profile > cpu.svg
go tool pprof http://localhost:6060/debug/pprof/heap
默认是采样对象分配,想查看实际内存使用,加上参数:
runtime.MemProfileRate = 1 // 设置为 1 会记录所有内存分配
- • Graphviz(dot) :
go tool pprof 依赖其生成图
- • pprof web UI:Google 官方支持,可以使用浏览器打开
pprof 火焰图
- • Visual Studio Code + Go Extension:集成
pprof 可视化支持
go tool pprof 依赖其生成图pprof 火焰图pprof 可视化支持
curl http://localhost:6060/debug/pprof/goroutine?debug=2
可以查看每个 goroutine 的调用栈,排查是否有异常卡住的协程。
curl http://localhost:6060/debug/pprof/trace > trace.out
go tool trace trace.out
浏览器中打开界面分析调度、网络、GC、syscall 等事件。
runtime.SetBlockProfileRate(1)
然后访问 /debug/pprof/block 分析锁等待、channel 阻塞等情况。
| 场景 | 建议 |
|---|---|
| CPU 占用高 | 使用 CPU profile,重点分析热点函数和算法 |
| 内存泄漏 | heap 分析 + 手动 GC,排查大对象或缓存未释放 |
| goroutine 爆炸 | 分析 /goroutine?debug=2,检查是否有泄漏 |
| 响应慢 / 死锁 | 使用 trace + block profile,检查锁或调度卡点 |
生产环境开启 pprof 时建议:
- 绑定本地或内网地址
- 增加访问权限控制(如加认证或 Nginx 屏蔽)
- 设置
/debug/pprof/的访问开关
# 1. 启动服务中加入
import _ "net/http/pprof"
go http.ListenAndServe("localhost:6060", nil)
# 2. CPU 分析(默认 30 秒)
go tool pprof http://localhost:6060/debug/pprof/profile
# 3. Heap 分析
go tool pprof http://localhost:6060/debug/pprof/heap
# 4. 生成火焰图
go tool pprof -svg ... > cpu.svg
# 5. Trace
curl http://localhost:6060/debug/pprof/trace > trace.out
go tool trace trace.out
到此这篇关于详解Go语言中pprof性能分析与debug调试技巧的文章就介绍到这了,更多相关Go pprof性能分析与debug调试内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!
您可能感兴趣的文章:
- 聊聊Golang性能分析工具pprof的使用
- go性能分析工具pprof的用途及使用详解
- Go 库性能分析工具pprof
- golang利用pprof与go-torch如何做性能分析
- golang debug调试的实现
- Goland 断点调试Debug的操作