Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon how can I profile both CPU and memory usage simultaneously in Go


how can I profile both CPU and memory usage simultaneously in Go


To profile both CPU and memory usage simultaneously in Go, you can use the `runtime/pprof` package. Here's a step-by-step guide:

Step 1: Enable CPU Profiling

1. Start CPU Profiling:

go
   f, err := os.Create("cpu.pprof")
   if err != nil {
       log.Fatal(err)
   }
   defer f.Close()
   if err := pprof.StartCPUProfile(f); err != nil {
       log.Fatal(err)
   }
   

2. Stop CPU Profiling:

go
   defer pprof.StopCPUProfile()
   

Step 2: Enable Memory Profiling

1. Start Memory Profiling:

go
   f, err := os.Create("mem.pprof")
   if err != nil {
       log.Fatal(err)
   }
   defer f.Close()
   runtime.GC()
   if err := pprof.WriteHeapProfile(f); err != nil {
       log.Fatal(err)
   }
   

Step 3: Analyze Profiles

1. Analyze CPU Profile:

bash
   go tool pprof -cpu cpu.pprof
   

2. Analyze Memory Profile:

bash
   go tool pprof -mem mem.pprof
   

Step 4: Visualize Profiles

1. Visualize CPU Profile:

bash
   go tool pprof -web cpu.pprof
   

2. Visualize Memory Profile:

bash
   go tool pprof -web mem.pprof
   

By following these steps, you can profile both CPU and memory usage simultaneously in your Go application.

Citations:
[1] https://github.com/golang/vscode-go/issues/1685
[2] https://reintech.io/blog/guide-golang-runtime-pprof-package-profiling-go-programs
[3] https://github.com/souvikhaldar/Profiling-Go-application
[4] https://stackoverflow.com/questions/5549180/is-it-possible-to-do-cpu-and-memory-profiling-in-simultaneously-in-jvisualvm
[5] https://jvns.ca/blog/2017/09/24/profiling-go-with-pprof/