在这个例子中,我将向你展示如何使用 Golang 的pprof包,以收集和可视化应用程序的性能数据。这些发现可以用来识别瓶颈和提高整体性能。你甚至可以看到哪一行花了多长时间。我指的是逐行的性能分析我个人设法将我的一个API的性能提高了60%。我建议你阅读一篇非常有价值的高性能围棋工作坊的文章。
安装
完整的安装指南在这里,但我认为只要运行go get -u github.com/google/pprof 命令就足够了。
应用程序
假设我们有一个HTTP API,其基本信息如下:
Path: /Users/inanzzz/Language/Go/src/github.com/inanzzz/game
Binary: /Users/inanzzz/Language/Go/src/github.com/inanzzz/game/bin/game
Server: http://0.0.0.0:8000
路由
在你的HTTP服务器的路由器上添加以下路由。你可以打开corepprof.go文件,看看这些路由的作用:
// router := github.com/julienschmidt/httprouter
router.HandlerFunc(http.MethodGet, "/debug/pprof/", pprof.Index)
router.HandlerFunc(http.MethodGet, "/debug/pprof/allocs", pprof.Index)
router.HandlerFunc(http.MethodGet, "/debug/pprof/goroutine", pprof.Index)
router.HandlerFunc(http.MethodGet, "/debug/pprof/heap", pprof.Index)
router.HandlerFunc(http.MethodGet, "/debug/pprof/profile", pprof.Profile)
router.HandlerFunc(http.MethodGet, "/debug/pprof/trace", pprof.Trace)
router.HandlerFunc(http.MethodGet, "/debug/pprof/symbol", pprof.Symbol)
导入_ "net/http/pprof" 包。就这样了!我们可以继续收集和可视化数据了。
数据的生成和收集
你必须不断地向你的一个端点发送许多请求,以便pprof能够收集数据,否则应用程序很快就会存在,你就没有时间收集数据。为此,我使用了一个k6脚本,但如果你愿意,你也可以在一个循环中使用cURL 命令。我将向GET http://0.0.0.0:8000/home 端点发送100个并发请求,持续10秒。
让我们发送一些请求并收集CPU数据。一旦你运行pprof 命令,你就必须运行你的请求脚本,或者反过来,只要你的速度快就可以了
发送请求
$ k6 run scripts/k6/home.js
收集数据
这将运行一段时间,所以要有耐心:
$ go tool pprof /Users/inanzzz/Language/Go/src/github.com/inanzzz/game/bin/game http://0.0.0.0:8000/debug/pprof/profile
// Result
Fetching profile over HTTP from http://0.0.0.0:8000/debug/pprof/profile
Saved profile in /Users/inanzzz/pprof/pprof.game.samples.cpu.018.pb.gz
File: game
Type: cpu
Time: Dec 28, 2019 at 2:15pm (GMT)
Duration: 30.01s, Total samples = 0
No samples were found with the default sample value type.
Try "sample_index" command to analyze different sample values.
Entering interactive mode (type "help" for commands, "o" for options)
数据的可视化
这个命令将打开你的浏览器http://localhost:8080/ui/ ,在那里你将看到图表:
$ go tool pprof -http=:8080 /Users/inanzzz/pprof/pprof.game.samples.cpu.017.pb.gz
这个命令只用于 "跟踪 "图的数据生成和可视化:
// Generate data.
$ wget http://0.0.0.0:8000/debug/pprof/trace?seconds=10 -O tracing
// Serve on the browser.
$ go tool trace tracing
2019/12/28 14:43:20 Parsing trace...
2019/12/28 14:43:21 Splitting trace...
2019/12/28 14:43:22 Opening browser. Trace viewer is listening on http://127.0.0.1:64056