How to profile benchmarks using the pprof tool?

Salah Eddine Taouririt picture Salah Eddine Taouririt · Apr 13, 2014 · Viewed 9.4k times · Source

I want to profile my benchmarks generated by go test -c, but the go tool pprof needs a profile file usually generated inside the main function like this:

func main() {
    flag.Parse()
    if *cpuprofile != "" {
        f, err := os.Create(*cpuprofile)
        if err != nil {
            log.Fatal(err)
        }
        pprof.StartCPUProfile(f)
        defer pprof.StopCPUProfile()
    }

How can I create a profile file within my benchmarks ?

Answer

simon picture simon · Apr 13, 2014

As described in http://golang.org/cmd/go/#hdr-Description_of_testing_flags you can specify the profile file using the flag -cpuprofile.

For example

go test -cpuprofile cpu.out