Sitemap

Profiling in Go using pprof

3 min readDec 4, 2024
Free Gophers Pack by MariaLetta

Profiling in the context of any programming language is a technique that is mostly used to find performance bottlenecks and optimize the code by identifying areas that require improvement; it involves dynamically analyzing a program to measure things like memory utilization, CPU time spent on specific functions, or the frequency of function calls.

You may collect comprehensive information on CPU, memory, and other runtime metrics with Go’s built-in “pprof” tool, which is frequently used for profiling.

Let’s look at an example of how to profile a program you have written:

  1. flag.String and Command-Line Flags:
var profile = flag.String("cpuprofile", "", "cpu profile to output file")

This defines a command-line flag -cpuprofile that lets you specify the name of the file where CPU profiling data will be written.

2. File Creation:

file, err = os.Create(*profile)
if err != nil {
log.Fatal(err)
}

If the -cpuprofile flag is provided, a new file is created with the specified name. Profiling data will be saved to this file.

3. Starting and Stopping CPU Profiling:

pprof.StartCPUProfile(file)
defer pprof.StopCPUProfile()

pprof.StartCPUProfile begins recording CPU profiling data and writes it to the specified file.

The defer statement ensures that pprof.StopCPUProfile is called before the program exits, flushing any remaining data to the file.

Check out example code and a simulation of work to demonstrate how profiling with pprof works. Download to follow along:

  1. Run the program with profiling enabled
go run main.go -cpuprofile=cpu.prof

2. Now use the pprof tool to analyze the data

go tool pprof --text main cpu.prof

If you see this error, it means the go tool pprof command expects a compiled binary file (e.g., main) along with the profiling data (cpu.prof).

The error indicates that the binary file is not present in the current directory hence you need to compile your Go program into a binary

go build -o main .

Now if you run

go tool pprof --text main cpu.prof

What if you want to visualize the data to generate a graphical representation?

Run

go tool pprof -http=:8080 main cpu.prof

But wait, the pprof tool uses Graphviz (a graph visualization software) to generate visual representations of the profiling data. Hence you need to install it.

For Ubuntu users like me,

sudo apt update
sudo apt install graphviz

Now if you run the command again

Open http://localhost:8080 in your browser to view interactive graphs.

Standby for the next article on how to profile Goroutines, interpreting profiling results and how engineer canidentify bottlenecks from the output.

--

--

godfreyowidi
godfreyowidi

No responses yet