How to Profile Go Programs Easily
You write Go programs and you want to make them run faster. But where do you put the effort? Instead of blindly optimizing code, you want to profile. Here’s how you can do it today, quickly and easily.

GoLand
Starting with GoLand 2019.1, JetBrains added a Profiler feature. (You have heard of JetBrains haven’t you? They make a bunch of excellent IDEs around IntelliJ IDEA for many different programming languages, Go being one of them.)
Here’s the blog announcing the feature.
It gives you nice flame graphs, call trees, CPU profiling, memory profiling, etc. However, if you try it today, you quickly realize one serious limitation: it only works on Go tests not your actual program running on real-life data. Bummer!
Well, there is a ticket for that so maybe soon, this issue will be mended. https://youtrack.jetbrains.com/issue/GO-7101
But what can you do now?
Using pprof
If you do some web searching, you realize that there is a way to profile CPU and memory usage built into Go itself. The name of the tool is pprof
.
Here are the links to articles regarding how to use this facility.
Wait, you don’t like looking at ASCII output? You don’t like running graphviz
to get the giant SVG file to peruse on a web browser? You say you want flame graphs and call trees that you can traverse with a GUI?
Because GoLand is making use of the same pprof
feature of Go for profiling tests, can’t you make use of pprof
to profile your program running normally and then feed the profile output into GoLand to view it?
Yes, you can! First, go ahead and modify your Go program to allow profiling like this:
Notice that the code above surrounds your main
function in your main package. The CPU profile code should be placed before the body of your main
function while the memory profile code should be placed after. (If you don’t care for memory profiling, you can forego adding the bottom part altogether.)
Run your program with the -cpuprofile
flag set to a file path that will contain the profile output. For example, if your program is named “awesome” and you want to store the profile output as /tmp/awesome-profile.out
, invoke it like this:
> awesome -cpuprofile=/tmp/awesome-profile.out {followed by rest of args to awesome...}
Loading the Profile Results Into GoLand
Now all you need to do is load up your Go project in GoLand and then use the “Import Profile Results” under the “Run” menu. Using the file explorer UI, load up the profile results, e.g. /tmp/awesome-profile.out
in the example above.

Now you can use all of the UX features of GoLand to peruse the profile results! Enjoy!