Go Profiling with pprof for Beginners

Updated 4 min read
Go Profiling featured image: cards for benchmarks, CPU profiles and pprof

Go profiling shows exactly where your program spends its time and memory, so you fix real bottlenecks instead of guessing. In this post, you will write a benchmark and record CPU and memory profiles. Next, you will read them with go tool pprof. Finally, you will add live profiling to a web server.

Because benchmarks come from the testing package, first review Go unit testing for beginners. Our example also compares string building methods from Go strings explained with examples.

What Is Go Profiling?

In short, a profiler watches a running program and takes samples. For example, the CPU profiler checks about 100 times per second which function is running. After a while, the busiest functions stand out clearly.

For example, think of a doctor’s check-up. Instead of guessing why you feel tired, the doctor runs tests and reads the numbers. Similarly, Go profiling replaces guesses with measurements.

ProfileWhat it shows
CPUWhich functions use the most processor time
Heap (memory)Where memory is allocated and still in use
GoroutineWhat every goroutine is doing right now
Block and mutexWhere goroutines wait on locks or channels

In general, you start with CPU and memory. The other two help when a program feels stuck rather than slow. For example, goroutines may pile up behind one busy mutex.

Step 1: Write a Benchmark

func JoinPlus(words []string) string {
	s := ""
	for _, w := range words {
		s += w + ","
	}
	return s
}

func JoinBuilder(words []string) string {
	var b strings.Builder
	for _, w := range words {
		b.WriteString(w)
		b.WriteByte(',')
	}
	return b.String()
}
func BenchmarkJoinPlus(b *testing.B) {
	for b.Loop() {
		JoinPlus(words) // words holds 1,000 strings
	}
}

func BenchmarkJoinBuilder(b *testing.B) {
	for b.Loop() {
		JoinBuilder(words)
	}
}

b.Loop() arrived in Go 1.24. Specifically, it runs the body as many times as needed for a stable result. On older versions, use for i := 0; i < b.N; i++ instead.

Step 2: Run and Compare

$ go test -bench=. -benchmem
BenchmarkJoinPlus-2         624   1613349 ns/op   3717275 B/op   1000 allocs/op
BenchmarkJoinBuilder-2    62240     17561 ns/op     34296 B/op     15 allocs/op

First of all, the -benchmem flag adds memory columns. Here the + version is about 90 times slower and makes 1,000 allocations per call. Your numbers will differ by machine, but the gap stays huge. Also, run benchmarks on a quiet machine, because other busy programs add noise to the results.

Step 3: Read a Go Profiling Report

$ go test -bench=JoinPlus -cpuprofile cpu.out -memprofile mem.out
$ go tool pprof -top -sample_index=alloc_space mem.out
      flat  flat%   sum%        cum   cum%
    2.26GB 99.88% 99.88%     2.26GB 99.88%  prof.JoinPlus

For instance, the diagram below shows the full Go profiling loop, from benchmark to fix.

Go Profiling diagram showing the loop of benchmark, record, read, fix and measure again

Measure with a benchmark, record a profile, find the hot function with pprof, fix it and measure again.

Reading flat and cum

In short, flat is time or memory spent inside the function itself. cum also includes everything it calls. So start with the highest cum value from your own code, then drill into its children.

$ go tool pprof -top -cum cpu.out
      flat  flat%   sum%        cum   cum%
         0     0%     0%      680ms 46.26%  prof.JoinPlus
      20ms  1.36%  1.36%      680ms 46.26%  runtime.concatstring3

Here runtime.concatstring3 is the + operator at work. In other words, the profile points straight at the string concatenation.

Go Profiling a Live Web Server

import (
	"log"
	"net/http"
	_ "net/http/pprof"
)

func main() {
	log.Fatal(http.ListenAndServe("localhost:6060", nil))
}

Here, the blank import adds pages under /debug/pprof/. Then you can grab a 30 second CPU profile from the running server.

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

Keep these pages on localhost or behind a login, because they reveal internal details. Also try go tool pprof -http=:8081 cpu.out, which opens an interactive graph in your browser.

Common Go Profiling Mistakes

Problem you seeWhy it happensHow to fix it
Benchmark result is 0 ns/opBecause the compiler removed unused work.So use b.Loop() or store the result.
Profile shows only runtime functionsBecause your own code is too fast to sample.So run longer with -benchtime=5s.
Slower code after a “fix”Because the change was not measured.So re-run the benchmark every time.
/debug/pprof open to the internetBecause the server listens on all interfaces.So bind to localhost only.

In fact, performance questions often appear in senior interviews. So practise with my Go interview questions and answers.

Official Resources

These pages come straight from the Go team, so they stay accurate and up to date.

Quick Recap

  • Go profiling measures where time and memory really go.
  • Benchmarks with -benchmem compare speed and allocations.
  • -cpuprofile and -memprofile record profiles for pprof.
  • flat is the function itself, while cum includes its callees.
  • Import net/http/pprof to profile a live server on localhost.

What’s Next?

At last, you can find and fix slow code. Next, we will ship it by building binaries for Windows, macOS and Linux with cross compilation.

Next lesson: Go Cross Compilation: Build for Any OS