Profiling Code I

Let’s learn how to profile code in Go.

Profiling is a process of dynamic program analysis that measures various values related to program execution to give us a better understanding of the program behavior. In this lesson, we are going to learn how to profile Go code to understand it better and improve its performance. Sometimes, code profiling can even reveal bugs in the code such as an endless loop or functions that never return.

The runtime/pprof standard Go package is used for profiling all kinds of applications apart from HTTP servers. The high-level net/http/pprof package should be used when we want to profile a web application written in Go. We can see the help page of the pprof tool by executing go tool pprof -help.

Profiling a command-line application

The code of the application is saved as profileCla.go and collects CPU and memory profiling data. What is interesting is the implementation of main() because this is where the collection of the profiling data takes place:

Get hands-on with 1200+ tech skills courses.