What tools does Go provide for profiling and benchmarking?
Quick Answer
For profiling, Go ships pprof, which can capture CPU profiles, heap/memory profiles, goroutine dumps, and mutex/block contention profiles, either programmatically (import _ "net/http/pprof" for a live HTTP endpoint) or via the testing package's -cpuprofile/-memprofile flags during tests. Profiles are analyzed with go tool pprof, which can render a call graph, a flame graph, or a top-N list of the most expensive functions by CPU time or allocations. For benchmarking, the testing package supports func BenchmarkXxx(b *testing.B) functions run with go test -bench=., which repeatedly calls the code under test to get a stable per-operation timing and allocation count, letting you compare implementations objectively rather than guessing at performance.
Detailed Answer
Go's built-in profiling and benchmarking tools are good enough that most Go developers never need a third-party alternative.
Writing and running a benchmark
func BenchmarkConcat(b *testing.B) {
parts := []string{"a", "b", "c", "d", "e"}
for i := 0; i < b.N; i++ {
var s string
for _, p := range parts {
s += p
}
_ = s
}
}
go test -bench=. -benchmem
BenchmarkConcat-8 5000000 250 ns/op 48 B/op 4 allocs/op
b.N is adjusted automatically by the testing framework until it gets a stable measurement. -benchmem adds allocation count and bytes-per-operation, which often matters as much as raw speed.
CPU profiling a program
import _ "net/http/pprof"
func main() {
go func() {
log.Println(http.ListenAndServe("localhost:6060", nil))
}()
// ... rest of the app ...
}
go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
This captures a 30-second CPU profile from a live, running process, without needing to restart it in any special mode.
Profiling during tests
go test -cpuprofile=cpu.prof -memprofile=mem.prof -bench=.
go tool pprof cpu.prof
(pprof) top10
(pprof) web # opens a visual call graph in a browser, if graphviz is installed
What to actually look for
top10 inside pprof shows the functions consuming the most CPU time or memory, cumulative and flat. A flame graph (go tool pprof -http=:8080 cpu.prof) visualizes the same data as nested bars, making it easy to spot one unexpectedly expensive function buried deep in a call chain. Benchmarks paired with -benchmem are the standard way to validate that an optimization actually helped, rather than assuming it did.