To use Go's built-in profiling tools (pprof) for CPU and memory profiling, you can follow these steps:
Import the necessary packages in your Go program:
import (
_ "net/http/pprof"
"net/http"
)
Define a handler function to expose the profiling endpoints with net/http
package:
func profileHandler(w http.ResponseWriter, r *http.Request) {
pprof.Handler.ServeHTTP(w, r)
}
Register the handler with a specific URL path, for example /debug/pprof
:
http.HandleFunc("/debug/pprof/", profileHandler)
Start an HTTP server to listen for profiling requests:
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
Run your program. Now, you can access the profiling endpoints using a web browser or command-line tools.
CPU Profiling:
http://localhost:6060/debug/pprof/profile
. It starts the CPU profiling for 30 seconds by default, and the profile will be written to a file when the profiling completes.seconds
query parameter: http://localhost:6060/debug/pprof/profile?seconds=10
. This will profile for 10 seconds.http://localhost:6060/debug/pprof/profile?seconds=0
. The profile file will be downloaded with a .pprof
extension.go tool pprof
command-line tool: go tool pprof profile.pprof
.Memory Profiling:
http://localhost:6060/debug/pprof/heap
. It captures a snapshot of the heap allocation.http://localhost:6060/debug/pprof/heap?debug=1
. This profile file will also have the .pprof
extension.go tool pprof heap.pprof
.Note: Make sure the code that enables pprof is only added in non-production environments, as exposing these endpoints may introduce security risks.