Profiling Our Tool

Learn how to analyze the programs for performance-related issues.

We'll cover the following...

Overview

Go provides several tools to help us analyze our programs for performance-related issues. We’ve already seen the benchmarking feature and how we can use it to accurately determine how fast our programs execute. In addition to benchmarks, Go provides two analytical tools to help us find contentions or bottlenecks in our programs: the profiling and tracing tools.

The Go profiler shows us a breakdown of where our program spends its execution time. By running the profiler, we can determine which functions consume most of the program’s execution time and target them for optimization.

We have two ways to enable profiling on our programs: by adding code directly to our program or by running the profiler integrated with the testing and benchmarking tools. The first approach requires that we maintain additional code in our application and control the profiling execution ourselves. The second approach tends to be easier since it’s already integrated with the benchmark tool, so we don’t need to add any more code to our program.

We’ll use this approach in this example since we already have a benchmark available.

Test the benchmark

Note: You can test our tool with the updated code files at the end of this lesson.

We run the benchmarks again, but this time, we enable the CPU profiler:

Press + to interact
go test -bench . -benchtime=10x -run ^$ -cpuprofile cpu00.pprof

We get the following output:

goos: linux
goarch: amd64
pkg: usercode/performance/colStats
Benchmark_Run-4 10 1012377660 ns/op
PASS
ok usercode/performance/colStats 11.438s

Press + to interact
ls

We get the following output:

benchresults00.txt colStats colStats.test cpu00.pprof
main.go main_test.go testdata

When we execute the profiler this way, it creates two files: the profile cpu00.pprof as specified in the command-line, and the compiled binary colStats.test.

Note: If you’re using a version of Go older than 1.10, ...