主要使用场景
了解golang进程的内部信息和定位性能问题
使用方式
- 你可以通过使用
runtime/pprof的方式,在本地生产cpu或者memory的prifle。这种比较适合跑一次的,跑完后看profile; - 也可以使用
runtime包,把相关的runtime指标暴露出来,自己收集展示。这种比较适合暴露打点给监控系统或其他外部系统用; - 还可以使用
net/http/pprof,直接在命令行或者web界面查看具体的profile信息。这种一般比较适合的长期运行的服务,比如web服务,
这里主要讲最后一种。
使用方式一般是在main.go中加入:
package main import ( "log" "net/http" _ "net/http/pprof" // import pprof here ) func main() { go func() { log.Println(http.ListenAndServe("localhost:8001", nil)) // use goroutine }() http.ListenAndServe(":8000", nil) }
web方式查看
打开127.0.0.0:8001/debug/pprof/地址可以看到如下的内容:
/debug/pprof/ Types of profiles available: Count Profile 0 allocs 0 block 0 cmdline 4 goroutine 0 heap 0 mutex 0 profile 7 threadcreate 0 trace full goroutine stack dump Profile Descriptions: allocs: A sampling of all past memory allocations block: Stack traces that led to blocking on synchronization primitives cmdline: The command line invocation of the current program goroutine: Stack traces of all current goroutines heap: A sampling of memory allocations of live objects. You can specify the gc GET parameter to run GC before taking the heap sample. mutex: Stack traces of holders of contended mutexes 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. threadcreate: Stack traces that led to the creation of new OS threads 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.
TODO:各项说明,以及子页面的字段说明。
- allocs
- block
- cmdline
- goroutine: 一般是查看goroutine的数量和具体的使用分布。比如线上应用的goroutine数量暴涨,就可以从这里入手,看看都用在哪了。
- heap
- mutex
- profile:获得cpu profile文件,下载了可以本地用go tool pprof命令查看。一般用来查看函数哪些地方cpu使用率高,然后进行针对的优化。
- threadcreate
- trace:获得trace文件, 下载了可以本地用go tool trace命令查看
如果程序是在服务器上,可以先生成个文件:
go tool pprof ./main http://127.0.0.1:8001/debug/pprof/profile
然后下载到本地再查看(带个binary,方便命令行使用list命令):
go tool pprof -http=:8001 ./main ~/pprof/pprof.main.samples.cpu.001.pb.gz
cli方式查看
go tool pprof ./main http://127.0.0.1:8001/debug/pprof/profile
常用的命令是top和list,可以通过help查看帮助。
TODO:cli列名含义说明
TODO:建个repo来演示和说明,有实际的指标可以看和展示。