Go pprof cheat sheet
As you know, “What is measured, improves”. So, if you can measure the performance of you application, you can improve it accordingly. Go programming language has pprof for measuring performance of your apps written in Go.
Enable profiling in Go application ๐
Default http server ๐
If you are using the default http server handler, enable profiling like that.
import (
_ "net/http/pprof"
"net/http"
)
//...
return http.ListenAndServe(":8081", nil)
Non-default server ๐
If you are using a custom http server handler, enable profiling like that.
import (
"net/http"
"net/http/pprof"
)
//...
mux := http.NewServeMux()
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
// ...
server := &http.Server{
Addr: ":8081",
Handler: mux,
}
return server.ListenAndServe()
Memory ๐
To gain access to pprof data in the Go service (e.g from Kubernetes).
kubectl -n my-ns port-forward svc/my-app 8081:8081
To get the memory profile.
curl -s http://127.0.0.1:8081/debug/pprof/heap > ./heap.pprof
To load and read profile.
go tool pprof -http=:8080 ./heap.pprof
Additional info for reading ๐
inuse_space
: amount of memory allocated and not released yet (important).inuse_objects
: amount of objects allocated and not released yet.alloc_space
: total amount of memory allocated (regardless of released).alloc_objects
: total amount of objects allocated (regardless of released).
CPU ๐
To gain access to pprof data in the Go service (e.g from Kubernetes).
kubectl -n my-ns port-forward svc/my-app 8081:8081
To get the CPU profile.
By default will be 30s
of CPU profile:
curl -s http://127.0.0.1:8081/debug/pprof/profile > ./cpu.pprof
To customize the time with ?seconds=N
:
curl -s http://127.0.0.1:8081/debug/pprof/profile?seconds=60 > ./cpu.pprof
To load and read CPU profile.
go tool pprof -http=:8080 ./cpu.pprof
or
go tool pprof -web cpu.pprof
CPU trace ๐
To gain access to pprof data in the Go service (e.g from Kubernetes).
kubectl -n my-ns port-forward svc/my-app 8081:8081
To get the CPU trace profile.
By default will be 1s
of CPU trace profile:
curl -s http://127.0.0.1:8081/debug/pprof/trace > ./cpu-trace.pprof
To customize the time with ?seconds=N
:
curl -s http://127.0.0.1:8081/debug/pprof/trace?seconds=60 > ./cpu-trace.pprof
To load and read profile of the CPU trace.
go tool trace -http=:8080 ./cpu-trace.pprof
I hope you enjoyed reading this post as much as I enjoyed writing it. If you know a person who can benefit from this information, send them a link of this post. If you want to get notified about new posts, follow me on YouTube , Twitter (x) , LinkedIn , and GitHub .