雑なメモ書き

気楽にいきます

Goのpprofをつかってみる(1)

素材等

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が開かれる

f:id:hiroyukim:20190129003605p:plain

f:id:hiroyukim:20190129003636p:plain

どこで、どれぐらいかかったのかはっきり分かる。 今回の場合は、メインが軽すぎたぽい。