Profile your golang benchmark with pprof

The tooling in golang is a huge benefit of the language, and we can do the profiling with pprof of a benchmark in go.

We will for that take the example of Dave Cheney :

package benchimport "testing"func Fib(n int) int {
if n < 2 {
return n
return Fib(n-1) + Fib(n-2)
func BenchmarkFib10(b *testing.B) {
// run the Fib function b.N times
for n := 0; n < b.N; n++ {

on our terminal :

go test -bench=. -benchmem -cpuprofile profile.out

We can also check for the memprofile :

go test -bench=. -benchmem -memprofile memprofile.out -cpuprofile profile.out

And then we can use pprof as we are used to do :

go tool pprof profile.out
File: bench.test
Type: cpu
Time: Apr 5, 2018 at 4:27pm (EDT)
Duration: 2s, Total samples = 1.85s (92.40%)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top
Showing nodes accounting for 1.85s, 100% of 1.85s total
flat flat% sum% cum cum%
1.85s 100% 100% 1.85s 100% bench.Fib
0 0% 100% 1.85s 100% bench.BenchmarkFib10
0 0% 100% 1.85s 100% testing.(*B).launch
0 0% 100% 1.85s 100% testing.(*B).runN

(on this example I used the cpu file, but you can also do the same with the memory file)

Then you can also with the list command check wat in the function takes time

(pprof) list Fib
1.84s 2.75s (flat, cum) 148.65% of Total
. . 1:package bench
. . 2:
. . 3:import "testing"
. . 4:
530ms 530ms 5:func Fib(n int) int {
260ms 260ms 6: if n < 2 {
130ms 130ms 7: return n
. . 8: }
920ms 1.83s 9: return Fib(n-1) + Fib(n-2)
. . 10:}

or event generate a graph with the web command (or png, pdf, … it also works):

(pprof) web


if you want to run only benchmark and not all the tests of your program you can also do the following command

go test -bench=. -run=^$ . -cpuprofile profile.out

using -run=^$ means =>run all test method that the name follow the following regexp, but ^$ select no test. So it only run benchmark ;)

Felipe Dutra Tine e Silva

Written by

Lead engineer at Mindgeek

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade