If you find that the CPU/memory usage of the service is too high, or the request response is slow, and you want to know which piece of code is causing the problem, pprof is here to help you with that.
- First, you need to import the pprof library in advance. It's simple; just add a few lines of code to the server code.
import (
"net/http"
_ "net/http/pprof"
)
func main() {
go func() {
http.ListenAndServe("localhost:8080", nil)
}()
// Main process
}
- Click on the profile in the image below, and it will collect 30 seconds of data and save it to the profile file.
Then run
go tool pprof -http :8081 ./profile
- Open
http://localhost:8081/ui/
In the upper left corner, you can select the legendary Flame Graph (Flame Graph):