How to Use CPU and Memory Profiles in CI

Use the runtime/pprof package to generate CPU and memory profiles in Go, then analyze them with go tool pprof in your CI pipeline.

Go does not provide built-in CPU or memory profiling flags for CI; instead, you must generate pprof profiles using the runtime/pprof package and analyze them with the go tool pprof command. Add profiling logic to your test or build script to capture CPU usage over time or memory allocations, then save the output to a file for inspection.

import (
	"os"
	"runtime/pprof"
)

func main() {
	// Start CPU profiling
	f, _ := os.Create("cpu.prof")
	pprof.StartCPUProfile(f)
	defer pprof.StopCPUProfile()
	defer f.Close()

	// Your application logic here
	// ...

	// Write memory profile
	mf, _ := os.Create("mem.prof")
	pprof.WriteHeapProfile(mf)
	mf.Close()
}

Run the analysis in your CI pipeline using:

go tool pprof -top cpu.prof
go tool pprof -top mem.prof