Profiling your Go applications is made easy by the Go ecosystem. In this blog post, we will explore how to use the github.com/pkg/profile package by Dave Cheney to easily debug and profile your programs.

To get started, follow these simple steps:

CPU Profiling

Step 1: Download github.com/pkg/profile by running the following command:

go get github.com/pkg/profile

Step 2: Add profiling to the main() function of your command:

package main

import (
 //...
 "github.com/pkg/profile"
)

func main() {
 // CPU profiling by default
 defer profile.Start().Stop()

 //...
}

Step 3: Build and run your program. This will generate a *.pprof file in a temporary folder and display its location:

2017/08/03 14:26:28 profile: cpu profiling enabled, /var/...../cpu.pprof

Step 4: Install graphviz if you haven’t already. On a Mac, you can simply run brew install graphviz. For other platforms, refer to https://www.graphviz.org.

Step 5: Run go tool pprof with your binary location and the location of the cpu.pprof file:

To generate a PDF analysis:

go tool pprof --pdf ~/go/bin/yourbinary /var/path/to/cpu.pprof > file.pdf

cpu profiling graph

You can also generate other types of visualizations, such as txt:

go tool pprof --txt ~/go/bin/yourbinary /var/path/to/cpu.pprof > file.txt

Memory Profiling

Memory profiling is similar to CPU profiling, but with a slight modification. Instead of using the default configuration for profile.Start(), we pass a profile.MemProfile flag:

defer profile.Start(profile.MemProfile).Stop()

Therefore, the updated code looks like this:

package main

import (
 //...
 "github.com/pkg/profile"
)

func main() {
 // Memory profiling
 defer profile.Start(profile.MemProfile).Stop()

 //...
}

When running the program, it will generate a mem.pprof file instead of cpu.pprof. memory profiling graph

For more information on profiling Go applications, you can refer to the following resources: