Go内置标准库
- runtime/pprof:采集工具型应用运行数据进行分析
- net/http/pprof:采集服务型应用运行时数据进行分析
工具型 runtime/pprof
pprof.StartCPUProfile(w io.Writer) // 开启CPU性能分析
pprof.StopCPUProfile() // 关闭cpu性能分析
然后会生成一个文件进行分析,使用命令
go tool pprof xxx.txt
pprof.WriteHeapProfile(w io.Writer) // 记录程序堆栈(内存)信息
然后同上使用命令
go tool pprof xxx.txt
服务型 net/http/pprof
import _ "net/http/pprof"
// 需要手动注册一些路由:
r.HandleFunc("/debug/pprof/", pprof.Index)
r.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
r.HandleFunc("/debug/pprof/profile", pprof.Profile)
r.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
r.HandleFunc("/debug/pprof/trace", pprof.Trace)
如果你使用的是gin框架,那么推荐使用"github.com/DeanThompson/ginpprof"。
go tool pprof
格式:
go tool pprof [binary] [source]
例如:
go tool pprof -cpu xxx.pprof
- binary 是应用的二进制文件,用来解析各种符号;
- source 表示 profile 数据的来源,可以是本地的文件,也可以是 http 地址。
进入pprof命令行
(pprof) top 3 // 查看占用前3
Showing nodes accounting for 100.37s, 87.68% of 114.47s total
Dropped 17 nodes (cum <= 0.57s)
Showing top 3 nodes out of 4
flat flat% sum% cum cum%
42.52s 37.15% 37.15% 91.73s 80.13% runtime.selectnbrecv
35.21s 30.76% 67.90% 39.49s 34.50% runtime.chanrecv
22.64s 19.78% 87.68% 114.37s 99.91% main.logicCode
- flat:当前函数占用CPU的耗时
- flat::当前函数占用CPU的耗时百分比
- sun%:函数占用CPU的耗时累计百分比
- cum:当前函数加上调用当前函数的函数占用CPU的总耗时
- cum%:当前函数加上调用当前函数的函数占用CPU的总耗时百分比
最后一列:函数名称
(pprof) list logicCode // 查看 logicCode函数占用情况
Total: 1.91mins
ROUTINE ================ main.logicCode in .../runtime_pprof/main.go
22.64s 1.91mins (flat, cum) 99.91% of Total
. . 12:func logicCode() {
. . 13: var c chan int
. . 14: for {
. . 15: select {
. . 16: case v := <-c:
22.64s 1.91mins 17: fmt.Printf("recv from chan, value:%v\n", v)
. . 18: default:
. . 19:
. . 20: }
. . 21: }
. . 22:}
图形化
(pprof)命令行,直接输入web,可以通过svg进入图形页面,需要提前安装:graphviz
mac可直接安装:
brew install graphviz
go-torch和火焰图
详情点击这里
安装go-touch
go get -v github.com/uber/go-torch