Evaluate PGO and version-specific optimization
Evaluate PGO and version-specific optimization
Profile-guided optimization (PGO) uses measured CPU profile data to inform compiler decisions such as inlining hot calls and devirtualizing some interface calls. Go 1.23 supports go build -pgo=profile.pprof; -pgo=off disables PGO and -pgo=auto uses default.pgo when applicable. It changes optimization heuristics, not language semantics. A stale or unrepresentative profile may fail to help. Compare equivalent workloads and verify correctness before drawing performance conclusions.
package main
import ( "fmt")
func work(n int) uint64 { var s uint64 for i := 0; i < n; i++ { s += uint64(i) * 3 } return s}func main() { fmt.Println(work(1000))}This workload provides a correctness oracle: the sum of 3*i for i from 0 to 999. To produce a profile, use a test benchmark calling work repeatedly and retain the result in a package-level sink, then run go test -run=^$ -bench=. -benchtime=2s -cpuprofile=cpu.pprof. Inspect with go tool pprof -top cpu.pprof. A valid profile is not itself proof of a performance improvement. Use the same package path and workload for profiling and optimized builds.
Expected output:
1498500Record the toolchain and behavior
package main
import ( "fmt" "runtime" "strings")
func work(n int) uint64 { var s uint64 for i := 0; i < n; i++ { s += uint64(i) * 3 } return s}func main() { fmt.Println(work(0), work(1), work(10)) fmt.Println(strings.HasPrefix(runtime.Version(), "go") || strings.HasPrefix(runtime.Version(), "devel"))}Build a baseline using go build -pgo=off -o baseline . and a candidate using go build -pgo=cpu.pprof -o candidate . in the same module. Run the same tests and inputs. For a meaningful benchmark compare repeated non-profiled benchmark runs using identical flags except PGO, on the same quiet machine; retain Go version, GOOS, GOARCH, inputs and profile provenance. This chapter verifies a local synthetic profile and paired builds, not a speedup or a newer compiler version.
Expected output:
0 0 135trueTry it locally
Implement work for the sum of squares from 0 to n-1. Print results for n=0, 3 and 5; use these as correctness checks before and after a PGO build.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Compiler pipeline 09: Evaluate PGO and version-specific optimization
Check the lesson objective before moving on.
What does PGO consume?
What should a baseline-versus-PGO comparison establish first?