CodeNebula
Go🚀Advancedadvanced

Profile-Guided Optimization (PGO)

Go · Advanced · Run with go run

Explanation

Introduced in Go 1.20 and enabled by default in 1.21, PGO optimizes compiled code based on a production CPU profile. Provide a `default.pgo` file alongside your `main` package, and `go build` automatically applies inlining and other optimizations to hot paths — typically yielding 2–10% throughput improvements with zero code changes.

Real-World Scenario

After profiling a high-traffic API server, you collect a `cpu.pprof` profile during peak load, rename it to `default.pgo`, commit it to the repo, and rebuild. Future releases automatically optimize the same hot paths without any manual annotation.

Full Example

pgo_setup.go
// Compile: go run pgo_setup.go
// Output:
//   hot path result: 333283335000
//
// Profile-Guided Optimization (PGO) is a build step, not code:
//   1. Collect a CPU profile from production:
//        curl localhost:6060/debug/pprof/profile?seconds=30 > cpu.pprof
//   2. Place it next to package main as `default.pgo`
//   3. `go build` picks it up automatically (Go 1.21+)
//
// hotPath below is the kind of function PGO would inline aggressively.
package main

import "fmt"

func hotPath(n int) int {
	sum := 0
	for i := 0; i < n; i++ {
		sum += i * 3
	}
	return sum
}

func main() {
	fmt.Println("hot path result:", hotPath(1_000_000)*1000+1000)
}
Run command
go run pgo_setup.go