/

Getting Started with Go CPU and Memory Profiling

Getting Started with Go CPU and Memory Profiling

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:

1
go get github.com/pkg/profile

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

1
2
3
4
5
6
7
8
9
10
11
12
13
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:

1
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:

1
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:

1
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:

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

Therefore, the updated code looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
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:

tags: [“Go”, “profiling”, “CPU profiling”, “memory profiling”, “debug”]