How to use Go's built-in profiling tools (pprof) for CPU and memory profiling?

To use Go's built-in profiling tools (pprof) for CPU and memory profiling, you can follow these steps:

  1. Import the necessary packages in your Go program:

    import ( _ "net/http/pprof" "net/http" )
  2. 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) }
  3. Register the handler with a specific URL path, for example /debug/pprof:

    http.HandleFunc("/debug/pprof/", profileHandler)
  4. Start an HTTP server to listen for profiling requests:

    go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }()
  5. Run your program. Now, you can access the profiling endpoints using a web browser or command-line tools.

    • CPU Profiling:

      • To enable CPU profiling, go to 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.
      • To start CPU profiling for a different duration, specify the seconds query parameter: http://localhost:6060/debug/pprof/profile?seconds=10. This will profile for 10 seconds.
      • After the profiling completes, you can download the profile file by visiting http://localhost:6060/debug/pprof/profile?seconds=0. The profile file will be downloaded with a .pprof extension.
      • Analyzing the downloaded profile can be done with the go tool pprof command-line tool: go tool pprof profile.pprof.
    • Memory Profiling:

      • To enable memory profiling, go to http://localhost:6060/debug/pprof/heap. It captures a snapshot of the heap allocation.
      • After visiting the endpoint, the memory profile can be downloaded by visiting http://localhost:6060/debug/pprof/heap?debug=1. This profile file will also have the .pprof extension.
      • Analyzing the downloaded memory profile is similar to CPU profiling: 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.