Getting started with Go CPU and memory analysis

The Go ecosystem provides a very simple way to analyze your application.

I will explain the use of Dave Cheney's software package for performance analysis, which makes the program very easy to debug by adding a single line of code to our program.main().

You just need to start performing the following X simple steps.

CPU analysis

Step 1: Downloadgithub.com/pkg/profile

Simpler than running

go get github.com/pkg/profile

That's it.

Step 2: Add the configuration file tomain()The function of your order

package main

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

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

<span style="color:#75715e">//...

}

Step #3: Generate and run the program

This will produce a*.pprofPut the file in a temporary folder and tell you its location (need later)

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

Step #4: install graphviz if you don’t have it installed yet

This is used to generate the graph on a pdf. On a Mac, it’s a simple brew install graphviz. Refer to https://www.graphviz.org for other platforms.

Step #5: run go tool pprof

Pass your binary location, and the location of the cpu.pprof file as returned when running your program.

You can generate the analysis in various formats. The PDF one is pretty amazing:

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

You can generate other kind of visualizations as well, e.g. txt:

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

Memory profiling

Memory profiling is essentially the same as CPU profiling, but instead of using the default configuration for profile.Start(), we pass a profile.MemProfile flag:

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

thus the code becomes

package main

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

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

<span style="color:#75715e">//...

}

and when running the program, it will generate a mem.pprof file instead of cpu.pprof.

Read more about profiling Go apps

This is just a start. Read more at:


More go tutorials: