索引
net/http/pprof
Package pprof serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool.
The package is typically only imported for the side effect of registering its HTTP handlers. The handled paths all begin with /debug/pprof/.
The handled paths all begin with /debug/pprof/.
To use pprof, link this package into your program:
import _ "net/http/pprof"
这个包只是封装上面的包,以http server的形式提供功能。
// /net/http/pprof/pprof.go
func init() {
http.HandleFunc("/debug/pprof/", Index)
http.HandleFunc("/debug/pprof/cmdline", Cmdline)
http.HandleFunc("/debug/pprof/profile", Profile)
http.HandleFunc("/debug/pprof/symbol", Symbol)
http.HandleFunc("/debug/pprof/trace", Trace)
}
使用import _ "net/http/pprof"
后,会添加 /debug/pprof/
,如果本身没有启动http server或者使用第三方的http库,需要手动添加代码启动http server。
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
功能列表
- profile
CPU profile. You can specify the duration in the seconds GET parameter. After you get the profile file, use the go tool pprof command to investigate the profile.
CPU 采样分析,按照一定的频率采集所监听的应用程序 CPU(含寄存器)的使用情况,可确定应用程序在主动消耗 CPU 周期时花费时间的位置
- trace
A trace of execution of the current program. You can specify the duration in the seconds GET parameter. After you get the trace file, use the go tool trace command to investigate the trace
- block
Stack traces that led to blocking on synchronization primitives
阻塞分析,记录 goroutine 阻塞等待同步(包括定时器通道)的位置
- cmdline
The command line invocation of the current program
查看当前程序命令行
- goroutine
Stack traces of all current goroutines
当前所有协程的堆栈跟踪
- mutex
Stack traces of holders of contended mutexes
互斥锁分析,报告互斥锁的竞争情况
- threadcreate
Stack traces that led to the creation of new OS threads
- allocs
A sampling of all past memory allocations
内存分析,目标是对所有对象
- heap
A sampling of memory allocations of live objects. You can specify the gc GET parameter to run GC before taking the heap sample.
内存分析,对活动的对象进行堆分配时记录堆栈跟踪,用于监视当前和历史内存使用情况,以及检查内存泄漏。
go tool pprof
使用go tool pprof <source>
可以进行性能采集
-
当
<source>
是url时,会从url进行采集保存为文件,并进入命令交互模式 -
当
<source>
是文件时,会自动进入命令交互模式 -
也可以添加
-http
使用基于web的交互模式
$ go tool pprof http://127.0.0.1:6060/debug/pprof/profile
$ go tool pprof -http=:8080 http://127.0.0.1:6060/debug/pprof/profile
参数说明
flat和flat%列代表该函数运行的时间/内存空间和占比
cum和cum%列代表该函数和子函数的运行时间/内存空间和占比
sum% 列代表当前行到第一行的flat%的总和
命令交互模式
web - Visualize graph through web browser
web命令会调用浏览器打开svg格式的可视化图像
火焰图
火焰图就是看顶层的哪个函数占据的宽度最大。只要有"平顶"(plateaus),就表示该函数可能存在性能问题。