Goのpprofをつかってみる(1)
- 参照先
- goにはprofiling toolがある
- pkg/runtime/pprof
- pkg/net/http/pprof
- 2種類存在していて、それぞれコマンドライン用ととサーバー用だと考えればいい
- 今回はコマンドラインベースで実行するやつ
素材等
main.go
実行方法
go test
test fileがある場合はgo testにオプションを追加して取得出来る
go test -cpuprofile cpu.prof -memprofile mem.prof -bench .
コードに追加
- main.goに以下を追記すればいい
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`") var memprofile = flag.String("memprofile", "", "write memory profile to `file`") func main() { flag.Parse() if *cpuprofile != "" { f, err := os.Create(*cpuprofile) if err != nil { log.Fatal("could not create CPU profile: ", err) } if err := pprof.StartCPUProfile(f); err != nil { log.Fatal("could not start CPU profile: ", err) } defer pprof.StopCPUProfile() } // ... rest of the program ... if *memprofile != "" { f, err := os.Create(*memprofile) if err != nil { log.Fatal("could not create memory profile: ", err) } runtime.GC() // get up-to-date statistics if err := pprof.WriteHeapProfile(f); err != nil { log.Fatal("could not write memory profile: ", err) } f.Close() } }
実行
go run main.go --cpuprofile=cpu.prof --memprofile=mem.prof
結果の表示
web uiで見た方がいい。
go tool pprof -http=localhost:8888 mem.prof
か
go tool pprof -http=localhost:8888 cpu.prof
どちらかでweb uiが開かれる
どこで、どれぐらいかかったのかはっきり分かる。 今回の場合は、メインが軽すぎたぽい。