Profile-guided optimization
suggest changeThe Go compiler makes its optimization decisions without knowing how your program runs. It doesn't know which functions are called millions of times per second and which run once at startup, so it applies the same rules everywhere.
Profile-guided optimization (PGO) gives the compiler a CPU profile of the program in real use. With a profile, the compiler optimizes the hot paths more aggressively.
PGO was a preview in Go 1.20 and became generally available in Go 1.21. Since Go 1.21, go build uses a profile automatically if the main package directory contains a file named default.pgo. Later releases taught the compiler to use the profile for more decisions and made PGO builds faster.
The workflow:
- Build and deploy your program as usual.
- Collect a CPU profile from production (or a realistic load test).
- Save the profile as
default.pgonext to yourmainpackage and commit it. - Rebuild. Repeat step 2 from time to time to keep the profile fresh.
What the compiler does with a profile
Currently the profile drives two optimizations:
- Inlining of hot functions. Normally the compiler inlines only functions whose estimated cost is under a budget of 80 (see Inlining functions). At call sites the profile marks as hot, it allows much larger functions to be inlined. In return, it can be stricter with cold code, which keeps the binary from growing too much.
- Devirtualization. A call through an interface (
r.Read(p)) is an indirect call, and the compiler can't inline it. If the profile shows that, at a given call site, the interface almost always holds one concrete type, the compiler adds a type check and a direct call:
// conceptually, for a call site where f is usually upper
if u, ok := f.(upper); ok {
dst[i] = u.Apply(b) // direct call, which can now be inlined
} else {
dst[i] = f.Apply(b) // fallback: the original indirect call
}
The fallback keeps the program correct for any other type. Current versions also devirtualize calls through function values in the same way.
Inlining matters beyond saving a call. Once the body is inlined, the compiler can apply other optimizations across the old call boundary, and escape analysis often keeps values on the stack instead of the heap (see Memory, escape analysis, and garbage collection).
A small example
This program does two things in a hot loop. It transforms bytes through a Filter interface, and it counts byte classes using classify, a function that is just over the inlining budget:
package main
import (
"flag"
"fmt"
"log"
"os"
"runtime/pprof"
"time"
)
// Filter is called once per byte of input, through an interface.
type Filter interface {
Apply(b byte) byte
}
type upper struct{}
func (upper) Apply(b byte) byte {
if b >= 'a' && b <= 'z' {
return b - 'a' + 'A'
}
return b
}
type rot13 struct{}
func (rot13) Apply(b byte) byte {
switch {
case b >= 'a' && b <= 'z':
return 'a' + (b-'a'+13)%26
case b >= 'A' && b <= 'Z':
return 'A' + (b-'A'+13)%26
}
return b
}
func transform(f Filter, dst, src []byte) {
for i, b := range src {
dst[i] = f.Apply(b)
}
}
// classify is too big for the default inlining budget.
func classify(b byte) int {
switch {
case b >= 'a' && b <= 'z':
return 1
case b >= 'A' && b <= 'Z':
return 2
case b >= '0' && b <= '9':
return 3
case b == ' ' || b == '\t' || b == '\n' || b == '\r':
return 4
case b == '.' || b == ',' || b == ';' || b == ':':
return 5
case b == '!' || b == '?' || b == '-' || b == '\'':
return 6
case b == '(' || b == ')' || b == '[' || b == ']':
return 7
}
return 0
}
func histogram(data []byte) [8]int {
var h [8]int
for _, b := range data {
h[classify(b)]++
}
return h
}
func makeInput(n int) []byte {
const text = "The quick brown fox jumps over the lazy dog, 42 times! (Really?) "
buf := make([]byte, n)
for i := range buf {
buf[i] = text[i%len(text)]
}
return buf
}
func pickFilter(name string) Filter {
if name == "rot13" {
return rot13{}
}
return upper{}
}
func main() {
cpuprofile := flag.String("cpuprofile", "", "write CPU profile to `file`")
filter := flag.String("filter", "upper", "upper or rot13")
rounds := flag.Int("n", 300, "number of rounds")
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
defer f.Close()
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatal(err)
}
defer pprof.StopCPUProfile()
}
src := makeInput(1 << 20)
dst := make([]byte, len(src))
f := pickFilter(*filter)
var h [8]int
start := time.Now()
for range *rounds {
transform(f, dst, src)
h = histogram(dst)
}
fmt.Printf("histogram: %v\n", h)
fmt.Printf("took: %v\n", time.Since(start).Round(time.Millisecond))
}
The compiler can't devirtualize f.Apply on its own: pickFilter returns a different type depending on a command-line flag. With -gcflags=-m=2 you can see why classify isn't inlined:
$ go build -pgo=off -gcflags=-m=2 . 2>&1 | grep -E 'classify|PGO'
./main.go:45:6: cannot inline classify: function too complex: cost 105 exceeds budget 80
Run the program with profiling turned on (the -cpuprofile flag is the pattern from Basic cpu and memory profiling) and look at the profile:
$ go build -o app && ./app -cpuprofile cpu.pprof
histogram: [0 0 742071 32264 193583 16132 32263 32263]
$ go tool pprof -top -nodecount=6 cpu.pprof
flat flat% sum% cum cum%
880ms 39.29% 39.29% 950ms 42.41% main.transform (inline)
740ms 33.04% 72.32% 1160ms 51.79% main.histogram (inline)
320ms 14.29% 86.61% 330ms 14.73% main.classify
130ms 5.80% 92.41% 2240ms 100% main.main
110ms 4.91% 97.32% 110ms 4.91% runtime.asyncPreempt
60ms 2.68% 100% 60ms 2.68% main.upper.Apply
main.classify and main.upper.Apply appear as separate functions, so they are real calls. Copy the profile to default.pgo and build again. No flag is needed, because -pgo=auto is the default:
$ cp cpu.pprof default.pgo
$ go build -gcflags=-m=2 . 2>&1 | grep -E '^./main.go.*(classify|PGO|inlining call to upper)'
./main.go:40:19: PGO devirtualizing interface call f.Apply to upper.Apply
./main.go:45:6: can inline classify with cost 105 as: func(byte) int { switch statement; return 0 }
./main.go:40:19: inlining call to upper.Apply
./main.go:68:13: inlining call to classify
Both hot calls changed: f.Apply became a guarded direct call to upper.Apply, which was then inlined, and classify was inlined although its cost is over 80.
I built both versions (go build -pgo=off -o nopgo and go build -o pgo) and ran them one after another, 10 times each. The times in milliseconds:
-pgo=off: 844 850 860 853 851 853 847 851 851 844 (median 851)
PGO: 821 807 814 790 798 796 794 791 791 809 (median 797)
That's about 6% faster. Measure on a quiet machine: in an earlier attempt, while other heavy processes were running, single runs of the same binary varied between 1.2 s and 2.1 s, and the difference between the builds was lost in that noise.
Collecting a profile from production
The best profile comes from the program doing its real work. For a server, that's easiest with net/http/pprof, which serves profiles over HTTP. This server renders Markdown with goldmark:
package main
import (
"bytes"
"flag"
"io"
"log"
"net/http"
_ "net/http/pprof" // registers /debug/pprof/ handlers on http.DefaultServeMux
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
)
var md = goldmark.New(goldmark.WithExtensions(extension.GFM))
func render(w http.ResponseWriter, r *http.Request) {
src, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 10<<20))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var buf bytes.Buffer
if err := md.Convert(src, &buf); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write(buf.Bytes())
}
func main() {
addr := flag.String("addr", ":8080", "public address")
debugAddr := flag.String("debug-addr", "localhost:6060", "pprof address")
flag.Parse()
// pprof lives on DefaultServeMux, served on a separate, private address
go func() {
log.Println(http.ListenAndServe(*debugAddr, nil))
}()
mux := http.NewServeMux()
mux.HandleFunc("POST /render", render)
log.Fatal(http.ListenAndServe(*addr, mux))
}
Importing net/http/pprof for its side effects registers handlers under /debug/pprof/ on http.DefaultServeMux. The public API uses its own ServeMux, and the default mux is served only on localhost. Never expose pprof endpoints to the internet: they reveal internals and a CPU profile request keeps the profiler running for as long as the client asks.
While the server is handling real traffic, fetch a CPU profile. seconds sets how long to sample (the default is 30):
$ curl -o cpu.pprof "http://localhost:6060/debug/pprof/profile?seconds=30"
For this article I generated load with a small client that posted a 1.7 MB Markdown file from 4 goroutines, and sampled for 10 seconds. The profile is a small file (77 KB here). It includes symbol information, so you don't need the binary to read it:
$ go tool pprof -top -nodecount=8 cpu.pprof
File: mdserver.exe
Type: cpu
Duration: 10s, Total samples = 46.70s (466.98%)
Showing nodes accounting for 14.12s, 30.24% of 46.70s total
Dropped 482 nodes (cum <= 0.23s)
Showing top 8 nodes out of 169
flat flat% sum% cum cum%
3.22s 6.90% 6.90% 14.23s 30.47% github.com/yuin/goldmark/parser.(*parser).parseBlock
2.36s 5.05% 11.95% 4.56s 9.76% runtime.scanObjectsSmall
2.32s 4.97% 16.92% 3.72s 7.97% runtime.tryDeferToSpanScan
1.55s 3.32% 20.24% 3.96s 8.48% github.com/yuin/goldmark/renderer/html.(*defaultWriter).RawWrite
1.32s 2.83% 23.06% 1.32s 2.83% github.com/yuin/goldmark/util.FindEmailIndex
1.22s 2.61% 25.67% 1.22s 2.61% runtime.memclrNoHeapPointers
1.10s 2.36% 28.03% 1.10s 2.36% runtime.semasleep
1.03s 2.21% 30.24% 1.03s 2.21% runtime.memmove
(I removed the Build ID and Time lines.) Total samples is more than the 10 s duration because the server used several CPU cores at once.
See Accessing Profile File for exploring a profile interactively.
Note that most of the hot code is in a third-party library and the runtime, not in the program's own main package. PGO applies to all packages linked into the binary, including dependencies and the standard library.
Other ways to get a profile:
- Programs that aren't servers: use
runtime/pprof.StartCPUProfileas in the example above, or add a flag that turns it on. - Benchmarks:
go test -cpuprofile cpu.pprof -bench .(see Using Benchmarks to Create Profile). This only works well if your benchmarks cover what production actually does. A profile from a single microbenchmark tells the compiler that one code path is all that matters. - Continuous profiling services that collect pprof profiles from a fleet. Their output can be used directly, often after merging.
Building with the profile
Put the profile in the directory of the main package under the name default.pgo:
mdserver/
go.mod
go.sum
main.go
default.pgo
Then build as usual. The -pgo flag of go build, go install, go run and go test controls which profile is used:
-pgo=auto(the default): for each main package in the build, usedefault.pgofrom that package's directory, if it exists.-pgo=off: don't use PGO.-pgo=path/to/file.pprof: use the given profile for every main package in the build.
The profile is applied to the main package and all of its dependencies. Only default.pgo files in main package directories are used, so a library has no reason to ship one. If you build several binaries at once, as with go build ./cmd/..., each command can have its own default.pgo, and each binary is built with its own profile.
Set GOFLAGS=-pgo=off in the environment to turn PGO off everywhere, for example to compare builds.
Checking that PGO was used
The build settings are recorded in the binary, and go version -m prints them:
$ go version -m mdserver.exe
mdserver.exe: go1.27.0
path example.com/mdserver
mod example.com/mdserver (devel)
dep github.com/yuin/goldmark v1.8.6 h1:d0VcaP1sx9GkFVkoW+KtggpGi2KZ965i14b0+bDQST4=
build -buildmode=exe
build -compiler=gc
build -pgo=C:\src\mdserver\default.pgo
build CGO_ENABLED=0
...
(I shortened the path to default.pgo.) A binary built without PGO has no -pgo line. You can also check this at run time with debug.ReadBuildInfo() from runtime/debug, by looking for the -pgo key in Settings.
To see what the compiler did with the profile, look for PGO devirtualizing in the -m output for all packages:
$ go build -gcflags='all=-m' . 2>&1 | grep 'PGO devirtualizing' | head -4
C:\Program Files\Go\src\runtime\malloc.go:1082:35: PGO devirtualizing function call mallocNoScanTable[size] to mallocgcSmallNoScanSC4
C:\Program Files\Go\src\runtime\malloc.go:1089:32: PGO devirtualizing function call mallocScanTable[size] to mallocgcSmallScanNoHeaderSC2
C:\Program Files\Go\src\regexp\backtrack.go:258:21: PGO devirtualizing interface call i.context to (*inputBytes).context
C:\Program Files\Go\src\regexp\exec.go:419:19: PGO devirtualizing interface call i.step to (*inputBytes).step
For the Markdown server, the compiler devirtualized 65 call sites, mostly goldmark's interface calls such as block.PeekLine to text.(*blockReader).PeekLine. The number of inlining call to lines went from 47,597 to 49,539.
PGO and go test
go test also uses -pgo=auto. When you test a main package that has a default.pgo, the test binary is built with it. Tests of other packages are built without a profile, because they don't belong to a main package. Pass the profile explicitly to benchmark a library package with it:
$ go test -pgo=$PWD/cmd/mdserver/default.pgo -bench . ./render
One trap: functions in package main are named main.classify in the program, but example.com/mdserver.classify in its test binary. A profile from the program doesn't match those functions in the test, so benchmarks of code in package main don't show the effect of PGO. Benchmark code that lives in a separate package.
Merging profiles
One profile from one server covers one period of time on one instance. Merging profiles from several instances or times of day gives a more representative picture. go tool pprof -proto merges profiles and writes the result in pprof format:
$ go tool pprof -proto cpu.pprof cpu2.pprof > merged.pprof
$ go tool pprof -top -nodecount=1 merged.pprof | grep Duration
Duration: 20s, Total samples = 96.69s (483.44%)
The two 10-second profiles became one 20-second profile. cpu2.pprof was collected from the binary built with PGO. That's fine: the Go team designed PGO so that a profile from a PGO-optimized binary works as input for the next build. You don't need to keep a non-PGO build around for profiling.
Profiles with many samples from a busy instance weigh more in the merge. If one instance had little traffic, its profile changes little in the result.
What to expect
The Go team reports that a set of representative Go programs gets between 2% and 14% faster with PGO (since Go 1.22; Go 1.21 typically gave 2% to 7%). The gain depends on the program: code with many interface calls in hot paths, or with hot functions that are just above the inlining budget, benefits more. Programs that spend their time in the garbage collector, in syscalls or waiting for the network, benefit less.
What I measured with Go 1.27 for this article:
| Test | Without PGO | With PGO | Difference |
|---|---|---|---|
| Small example above, 10 alternating runs, median | 851 ms | 797 ms | about 6% faster |
goldmark Convert of a 1.7 MB file, benchmark, benchstat over 15 alternating runs |
20.79 ms ± 2% | 20.04 ms ± 1% | 3.6% faster (p=0.000) |
| Markdown HTTP server, load client on the same machine, 5 alternating 10 s runs, average | 120.4 req/s | 121.2 req/s | lost in the noise (runs varied from 110 to 132 req/s) |
The benchmark numbers came from these two commands; the first builds two test binaries for comparing:
$ go test -c -pgo=off -o off.test.exe .
$ go test -c -pgo=default.pgo -o pgo.test.exe .
Each binary then ran with -test.bench=. -test.benchtime=40x, alternating, and benchstat (from golang.org/x/perf/cmd/benchstat) compared the results:
│ off3.txt │ pgo3.txt │
│ sec/op │ sec/op vs base │
Convert-24 20.79m ± 2% 20.04m ± 1% -3.61% (p=0.000 n=15)
The server test shows why careful measurement matters: the load client ran on the same machine, the server spends a big part of its time in the garbage collector (runtime.scanObjectsSmall and friends in the profile above), and a 2-4% gain is smaller than the variation between runs. Run the same benchmark on a quiet machine, alternate the builds, repeat many times, and use benchstat to check whether a difference is real.
Costs:
- Binary size: the Markdown server grew from 11,105,280 to 11,359,744 bytes (2.3%), because of the extra inlining.
- Build time: the first PGO build recompiles the standard library and all dependencies with the profile, so it can't reuse cached packages from non-PGO builds. Go 1.23 made the PGO overhead much smaller; before that, large builds could take twice as long. With Go 1.27, a full rebuild (
go build -a) of the Markdown server took 6.0 s without PGO and 6.4 s with it, in a single run each.
Keeping profiles fresh
Commit default.pgo to your repository. That makes builds reproducible: anyone who builds the same commit gets the same binary.
The source code changes after you collect a profile. The compiler matches profile samples to functions by name and to lines by their offset from the start of the function, so:
- Changes elsewhere in a file don't break the profile.
- Small edits inside a hot function lose only some of the information for that function.
- Renaming or moving a hot function, or a big refactoring, makes the old profile useless for that code. The compiler then just doesn't optimize it with PGO; the code is still correct.
PGO never makes the program incorrect, even with a completely stale profile. In the worst case, a stale profile wastes some binary size on code that is no longer hot.
A simple routine that works for most projects:
- Release a version built with the current
default.pgo. - After it has run in production for a while, collect profiles from several instances and merge them.
- Replace
default.pgowith the merged profile and commit it.
Doing this every release, or every few releases, is enough. Some teams automate it in CI by downloading the latest merged profile from their continuous profiling service.
Summary
- Collect a CPU profile under real load:
net/http/pproffor servers,runtime/pproffor other programs. - Save it as
default.pgonext to themainpackage;go builduses it automatically. - Use
-pgo=offto compare, andgo version -mto verify the build. - Merge profiles from several instances with
go tool pprof -proto. - Expect a few percent of CPU savings, and measure carefully before and after: see Performance for other optimization techniques.