How to Use pprof for Production Profiling in Go

Use runtime/pprof to capture profiles and go tool pprof to analyze performance bottlenecks in Go applications.

Use runtime/pprof to capture CPU, memory, or block profiles at runtime, then analyze them with go tool pprof.

package main

import (
	"net/http"
	_ "net/http/pprof"
	"os"
	"runtime/pprof"
	"time"
)

func main() {
	// Start CPU profiling
	f, _ := os.Create("cpu.prof")
	pprof.StartCPUProfile(f)
	defer pprof.StopCPUProfile()

	// Run your workload
	time.Sleep(10 * time.Second)

	// Serve pprof endpoints for interactive analysis
	go func() {
		http.ListenAndServe("localhost:6060", nil)
	}()

	// Wait for analysis
	time.Sleep(30 * time.Second)
}

Run go tool pprof cpu.prof to visualize the profile.