Profiling Go code

Posted on July 11, 2020


Profiling a Go program is relatively simple. First we have to import "runtime/pprof" and add some code:


func main() {
	// CPU profile
	if path := os.Getenv("CPUPROFILE"); path != "" {
		f, err := os.Create(path)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	// ... (Your code here)

	// Memory profile
	if path := os.Getenv("MEMPROFILE"); path != "" {
		f, err := os.Create(path)
		if err != nil {
			log.Fatal(err)
		}
		pprof.WriteHeapProfile(f)
		f.Close()
	}
}

This code enables CPU and memory profiling if the CPUPROFILE and MEMPROFILE environment variables are set. It will then write the profile results to the path provided in the respective environment variable.


For example, the following writes the results of a CPU profile to "example.cpuprof":


# CPU profile
env CPUPROFILE=example.cpuprof go run example

And the following writes the results of a memory profile to "example.memprof":


# Memory profile
env MEMPROFILE=example.memprof go run example

We can then view the results with "go tool pprof". The following command generates a graph and opens it in your web browser:


go tool pprof -web example.memprof

Note that you need to have "graphviz" installed to render the graph.


For more information, see:

Profiling Go Programs


---

This work is licensed under a CC-BY-SA-4.0 license.

Source code


Have a comment on one of my posts?

Send an email