pprof
Go のプロファイリングツール
どれも pprofという名前なのでややこしい。それぞれ単独で動かすこともできる
cmd/pprof
go tool pprof command
net/http/pprof
http server のプロファイル。内部的には runtime/pprof を呼んでいる
pkg/profile
runtime/pprof をラップしたもの
runtime/pprof
google/pprof
pprof command を提供
上記のプロファイラーを包含するものらしい
コードのプロファイルを取得する
導入
code:go
import "github.com/pkg/profile"
func main() {
defer profile.Start().Stop()
...
}
計測
プログラムを実行
HTTPサーバーのプロファイルを取得する
導入
http.DefaultServeMux を使っている場合 -> import の追加のみ
code:go
import (
_ "net/http/pprof"
)
使っていない場合 -> impor の追加に加えて、router の追加が必要
http.DefaultServeMux なら init でこれが注入される
https://github.com/golang/go/blob/c894b442d1e5e150ad33fa3ce13dbfab1c037b3a/src/net/http/pprof/pprof.go#L80
計測
サーバーを立てる
go tool pprof <server URL>/debug/pprof/profile でアクセスする
cpu profile の場合デフォルト30sで終了する
テストのプロファイルを取得する
go test -cpuprofile cpu.pprof みたいにやるとテスト実行中のプロファイルが取れる
プロファイルの種類
デフォルトでは CPU Profile のみが有効
Memory, Block など追加する場合
https://pkg.go.dev/github.com/pkg/profile?utm_source=godoc#example-CPUProfile
プロファイルの解析
CLIで解析
go tool pprof <path to binary> <path to profile>
画像に書き出す
go tool pprof -png <binary> out > <output.png>
webUI で解析
graphviz が必要
go tool pprof -http=":<port>" <server URL>/debug/pprof/profile
ref
https://github.com/DataDog/go-profiler-notes/blob/main/guide/README.md
DataDog がいい感じにまとめてくれている
https://christina04.hatenablog.com/entry/golang-pprof-basic
https://zenn.dev/muroon/articles/adf577f563c806?utm_source=pocket_mylist