How to profile and analyze CPU and memory usage of a Go program using runtime/pprof?

Profiling and analyzing the CPU and memory usage of a Go program can be done using the runtime/pprof package. Follow these steps to profile and analyze your Go program:

Step 1: Import the required packages

import ( "os" "runtime/pprof" )

Step 2: Create a profiling file

file, err := os.Create("profile.cpu") if err != nil { log.Fatal(err) } defer file.Close()

Step 3: Start CPU profiling

if err := pprof.StartCPUProfile(file); err != nil { log.Fatal(err) } defer pprof.StopCPUProfile()

Step 4: Run your Go program

$ go run main.go

Step 5: Create a memory profiling file

memFile, err := os.Create("profile.mem") if err != nil { log.Fatal(err) } defer memFile.Close()

Step 6: Write memory profiling data to the file

if err := pprof.WriteHeapProfile(memFile); err != nil { log.Fatal(err) }

Step 7: Analyze the CPU profile

$ go tool pprof -http=:8080 profile.cpu

This will open an interactive web interface to analyze the CPU profile. You can navigate through different profiling information such as top functions and call graphs.

Step 8: Analyze the memory profile

$ go tool pprof -http=:8080 -alloc_space profile.mem

This will open an interactive web interface to analyze the memory profile. You can view the memory allocation and usage by different functions or objects.

Note: Replace "main.go" with the name of your Go program file, and adjust the file names and paths as necessary.

This is a basic example of how to use runtime/pprof to profile and analyze CPU and memory usage of a Go program. You can explore more advanced profiling options and techniques provided by the package to get deeper insights into your program's performance.