1. 使用
import _ "net/http/pprof"func main() {http.ListenAndServe("0.0.0.0:6060", nil) // 启动服务
}
2. 分析
2.1 分析内存
第一步:打开 pprof
控制台
go tool pprof http://127.0.0.1:6060/debug/pprof/heap
第二步:查看占用内存最多的一些函数信息。
然后在控制台输入
top 10
flat: 本函数占用的内存量
flat%: 本函数内存占使用内存总量的百分比
sum%: 前面每一行flat百分比的和
cum: 累计量,main函数调用了函数f,函数f占用的内存量,也会记录进来
cum%: 累计量占总量的百分比
就会列出消耗内存 top 10 的函数方法。比如有一个方法命叫 RoundTrip
第三步
list RoundTrip
这个时候会出现更详细的代码位置
2. 分析 go runtine
第一步:打开 pprof
控制台
go tool pprof http://127.0.0.1:6060/debug/pprof/goroutine
第二步和第三步 和 上边的基本一样。
3. 优化
- 发现有内存泄漏,或者过多的内存占用,可以及时释放资源。
- 发现有 goruntine 泄漏,或者过多的 goruntine 队列,可以采用
github.com/panjf2000/ants
这个库来节省 goruntine 的开销。