How do I use pprof for CPU profiling?

Pprof is a tool for visualization and analysis of profiling data in Go. It can help you understand where your program spends most of its time, which is invaluable for optimizing performance. Below is a guide on how to use pprof for CPU profiling.

How to Use Pprof for CPU Profiling in Go

  1. Import the pprof package in your Go program:
  2. import (
        "net/http"
        "net/http/pprof"
    )
    
  3. Register pprof handlers with the default HTTP mux:
  4. func main() {
        // Register pprof handlers
        go func() {
            log.Println(http.ListenAndServe("localhost:6060", nil))
        }()
    
        // Your application code here
    }
    
  5. Run your program and make some requests to simulate CPU usage.
  6. Open your browser and navigate to http://localhost:6060/debug/pprof/ to view the profiling data.

You can also interact with the pprof tool using the command line:

go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30

pprof Go profiling CPU profiling Go performance profiling tools optimize Go application