how to get a pprof cpu profile written to disk?

1,189 views
Skip to first unread message

Jason E. Aten

unread,
Feb 7, 2017, 4:55:33 PM2/7/17
to golang-nuts
How does one reliably obtain a cpu profile written to file?  I tried following the instructions in runtime/pprof.go, but the profile file is most always empty... only on some magical moments can I discover a profile file being written to disk.

I also tried calling f.Sync() on the file hanlde f, from main (below) every minute, but that didn't help.

Supposedly the profiler is sampling at 100Hz, but I can't seem to get any samples.

repro code:
$ cat addack.go
package main

import (
    "fmt"
    "log"
    //"net/http"
    _ "net/http/pprof"
    "os"
    "runtime/pprof"
)

const ProgramName = "profileme"

func main() {

    f, err := os.Create(fmt.Sprintf("./addack-cpu-profile.%v", os.Getpid()))
    if err != nil {
        log.Fatal(err)
    }
    pprof.StartCPUProfile(f)
    defer pprof.StopCPUProfile()

    massiveAddack()
}

func massiveAddack() {
    m := 0
    for {
        m = addSub(m)
        fmt.Printf("m=%v\n", m)
    }
}

func addSub(n int) int {
    for i := 0; i < 1000000000; i++ {
        n += i * i
    }
    return n
}

 $ go run addack.go
m=3338615082255021824
m=6677230164510043648
m=-8430898826944486144
m=-5092283744689464320
m=-1753668662434442496
m=1584946419820579328
^Csignal: interrupt
$
$ ls -al|grep addack-cpu-profile.31523
-rw-rw-r--    1 jason  staff           0 Feb  7 15:50 addack-cpu-profile.31523  ## hmm.... profile file is always empty
 $

Dave Cheney

unread,
Feb 7, 2017, 5:01:04 PM2/7/17
to golang-nuts
^C will exit the program before the defer in your main can run.

I recommend using my profiling package, github.com/pkg/profile

andrey mirtchovski

unread,
Feb 7, 2017, 5:02:25 PM2/7/17
to Jason E. Aten, golang-nuts
your program never completes, pprof.StopCPUProfile() has no chance of
being called.
> --
> You received this message because you are subscribed to the Google Groups
> "golang-nuts" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to golang-nuts...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

Jason E. Aten

unread,
Feb 7, 2017, 5:03:30 PM2/7/17
to golang-nuts
addendum: the real program I'm trying to profile never exits on its own. It acts as a server. So I'd like to be able to profile it  without shutting it down (ideally), or by sending it a signal. I tried the web interface instead of the file, but I always get "empty profile" back.

Dave Cheney

unread,
Feb 7, 2017, 5:18:09 PM2/7/17
to golang-nuts
net/http/pprof is your best option

If you can't make that fly, then you can use my profile package; just keep a reference to the value returned from profile.Start() and call its Stop method to write out the profile
Reply all
Reply to author
Forward
0 new messages