How to Profile a Go Program with pprof

Profile a Go program by recording CPU usage to a file with runtime/pprof and analyzing it with go tool pprof.

Use the runtime/pprof package to record CPU usage to a file, then analyze it with the go tool pprof command.

package main

import (
	"os"
	"runtime/pprof"
)

func main() {
	f, _ := os.Create("cpu.prof")
	defer f.Close()
	pprof.StartCPUProfile(f)
	defer pprof.StopCPUProfile()
	// Your code here
}

Run the analysis:

go tool pprof cpu.prof

Or view in a browser:

go tool pprof -http=:8080 cpu.prof