go tool pprof 使い方メモ
参考文献
主に以下の URL にいろいろ書いてある.
Profiling Go Programs - The Go Blog
使い方
例えば以下の様なテンプレートで, run() 部分でロジックを記述するような形で使える(はず)
package main import ( "flag" "log" "rumtime/pprof" ) func run() { } var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file") var memprofile = flag.String("memprofile", "", "write memory profile to this file") func main() { flag.Parse() if *cpuprofile != "" { f, err := os.Create(*cpuprofile) if err != nil { log.Fatal(err) } pprof.StartCPUProfile(f) defer pprof.StopCPUProfile() } run() if *memprofile != "" { f, err := os.Create(*memprofile) if err != nil { log.Fatal(err) } pprof.WriteHeapProfile(f) f.Close() } }
ビルドして cpuprofile や memprofile を指定することでそれぞれのプロファイルデータが取れる.
$ go build -o main $ ./main --cpuprofile=cpu.pprof --memprofile=mem.mprof
プロファイルの中身を見る場合は go tool pprof を使う.使う場合は 引き数に実行バイナリと prof ファイルを指定する. メモリの場合も go tool pprof で同じようにファイル名を指定すると go tool pprof 側でメモリの結果を出力してくれる.
$ go tool pprof main cpu.pprof (pprof) top Total: 8143 samples 1925 23.6% 23.6% 4936 60.6% hash_insert 1455 17.9% 41.5% 1964 24.1% evacuate 943 11.6% 53.1% 943 11.6% runtime.aeshash64 773 9.5% 62.6% 1043 12.8% runtime.mapaccess2_fast64 386 4.7% 67.3% 6771 83.2% main.Input.isElegant 299 3.7% 71.0% 299 3.7% scanblock 220 2.7% 73.7% 220 2.7% sweepspan 207 2.5% 76.2% 207 2.5% runtime.memcopy64 202 2.5% 78.7% 5257 64.6% runtime.mapassign1 164 2.0% 80.7% 164 2.0% runtime.memclr
コールグラフを図で観たい場合は下記のように --svg などを指定する.
$ go tool pprof --svg main cpu.pprof > callgraph.svg
使える出力形式は go tool pprof のヘルプで見られる.
$ go tool pprof ... Output type: --text Generate text report --callgrind Generate callgrind format to stdout --gv Generate Postscript and display --web Generate SVG and display --list=<regexp> Generate source listing of matching routines --disasm=<regexp> Generate disassembly of matching routines --symbols Print demangled symbol names found at given addresses --dot Generate DOT file to stdout --ps Generate Postcript to stdout --pdf Generate PDF to stdout --svg Generate SVG to stdout --gif Generate GIF to stdout --raw Generate symbolized pprof data (useful with remote fetch) ...