There’s an old blog post floating around on the Go Blog with instructions on how to profile your code using pprof - except it’s out of date and might confuse some people. Here’s an up-to-date (as of Go 1.1) way to profile your code.
- import runtime/pprof
- Where you want the CPU profiling to start, you write:
pprof.StartCPUProfile(f) defer pprof.StopCPUProfile()
This has the effect of starting the profiler and then ending it once the containing function (often your “main” function) exits. The argument you pass to StartCPUProfile, “f”, is an open file descriptor to which the profile information will be written to. You can create this file by writing:
f, err := os.Create("my_profile.file")
- OK we have our profiling code setup. Now, build your binary. Let’s say my go file is called “foo.go”, I would run “go build foo.go”. This will create a binary called “foo”.
- Run your binary (e.g. ./foo)
- Now you run “go tool pprof foo my_profile.file” and you will be in the pprof interactive prompt. Here you can issue commands like top10 or top50 etc. Read up on pprof to find out all the commands you can enter.