💾 Archived View for adnano.co › 2020 › 07 › 11 › profiling-go-code captured on 2023-06-14 at 14:03:14. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2023-04-19)
-=-=-=-=-=-=-
Posted on 2020-07-11
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:
---
This work is licensed under a CC-BY-SA-4.0 license.