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