Profiling an application can help you understand its performance characteristics and identify bottlenecks or areas for optimization. Go provides a built-in profiling tool called ‘pprof‘ that enables you to profile applications easily.
‘pprof‘ is both a library that you can include in your application’s code and a command-line tool for analyzing profile data. In this answer, I will describe:
1. How to include the ‘pprof‘ library in your application
2. How to generate and save profile data
3. How to analyze and visualize the data using the ‘pprof‘ command-line tool
## 1. Including the ‘pprof‘ library in your application
First, you need to import the ‘net/http/pprof‘ package in your Go application. Once you’ve imported that package, you can add a new HTTP handler that will serve profile data.
Here’s an example of how to do this:
package main
import (
"fmt"
"net/http"
_ "net/http/pprof" // Important: Import pprof but use the blank identifier to avoid compile-time error for unused import
)
func main() {
fmt.Println("Starting server on http://localhost:8080")
http.ListenAndServe("localhost:8080", http.DefaultServeMux)
}
After running this example, you’ll have a basic HTTP server with the pprof HTTP handler enabled. This server exposes several pprof endpoints at ‘/debug/pprof/‘.
## 2. Generating and saving profile data
To create a CPU profile, issue an HTTP request to ‘/debug/pprof/profile‘ while your application is running. The default duration to collect CPU data is 30 seconds, but you can change this by providing the ‘seconds‘ parameter in the request.
Here’s how you can use ‘curl‘ to generate and save a CPU profile:
curl http://localhost:8080/debug/pprof/profile?seconds=60 --output cpu.pprof
Similarly, you can create a memory profile by issuing an HTTP request to ‘/debug/pprof/heap‘. To save the memory profile, use:
curl http://localhost:8080/debug/pprof/heap --output mem.pprof
## 3. Analyzing and visualizing profile data with ‘pprof‘ command-line tool
Once you have generated and saved the profile data, you can use the ‘pprof‘ command-line tool to analyze it. To install ‘pprof‘, run:
go get -u github.com/google/pprof
Now, you can use ‘pprof‘ in different ways, such as generating a text report or a graphical visualization of the profile data.
### CPU profile
To analyze the CPU profile you saved earlier (as ‘cpu.pprof‘), you can run the following command:
pprof -http=:8081 cpu.pprof
This command starts a web server at ‘http://localhost:8081‘ with an interactive GUI that allows you to explore the profile data.
If you prefer a text report, you can generate one using the ‘top‘ command:
pprof -top cpu.pprof
### Memory profile
Similarly, you can analyze the memory profile file (as ‘mem.pprof‘) by running:
pprof -http=:8081 mem.pprof