How to profile a Go application with pprof
Step 1
Install dependencies:
apt-get install graphviz gv
or
brew install graphviz
Step 2
Download pprof to your application
go get -u github.com/google/pprof
Step 3
Import pprof to your application
import _ "net/http/pprof"
Step 4
Add pprof server to application e.g. main.go
package main
import (
"fmt"
"sync"
_ "net/http/pprof"
)
func main() {
var wg sync.WaitGroup
// Server for pprof
go func() {
fmt.Println(http.ListenAndServe("localhost:6060", nil))
}()
wg.Add(1) // pprof - so we won't exit prematurely
wg.Wait()
}
Analysis
Memory
Access heap pprof report e.g. via port forwarding
go tool pprof http://localhost:PORT/debug/pprof/heap
then type png
you will get an image report about heap usage of your application
Go Routines
Access heap pprof report e.g. via port forwarding
go tool pprof http://localhost:PORT/debug/pprof/goroutine
then type png
you will get an image report about methods with high go routine count
Further analysis:
- CPU:
profile?seconds=10
- Goroutine blocking:
block
- Locks:
mutex
- Tracing:
trace?seconds=5