FlameGraphs for Code Optimization with Golang and SpeedScope.
Profiling your Go programs for cpu and memory is easy and built into the go tooling (for free). I used to follow Fransesc Campoy’s Go Tooling in Action video to demonstrate how to do profiling, one part of which is getting some amazing flame charts to pin-point where your application is using resources most. Follow his video tutorial to learn how you can improve the performance of your Go programs.
In a nutshell, X-axis is time and Y-axis is the call stack. Finding the functions you wrote that has long spreads on the X-axis could help you identify areas you could rewrite for performance.
Go tooling provides an easy way to generate the profiles, but visualizing them is a common task across languages and therefore the latter part requires one to install some graphing tools — GraphViz, go-torch, and pprof. Honestly, it’s easy, but it could be easier.
Today i came across an online app that allows you to do the same: SpeedScope.app.
Here’s a quick way to try this.
Step 1: create a new directory and cd into it.
mkdir mydir && cd mydir
Step 2: Copy the code from the below into a file named, say, mycode_test.go
package mypkgimport (
"log"
"regexp"
"strings"
"testing"
)var (
s = "The quick brown fox"
r = "^The.*$"
pat = "The"
)func BeginsWithRegex(s, r string) bool {
ok, err := regexp.MatchString(r, s)
if err != nil {
log.Println(err)
}
return ok}func BeginsWithString(s, pat string) bool {
return strings.HasPrefix(s, pat)
}func Benchmark_BeginsWithRegex(b *testing.B) {
for n := 0; n < b.N; n++ {
BeginsWithRegex(s, r)
}
}func Benchmark_BeginsWithString(b *testing.B) {
for n := 0; n < b.N; n++ {
BeginsWithString(s, pat)
}
}
Step 3: Run the following commands on the command line which will benchmark the two functions and create the corresponding cpu profile files.
go test -bench=BeginsWithString -cpuprofile=cpuprof_string.outgo test -bench=BeginsWithRegex -cpuprofile=cpuprof_regex.out
Step 4: Open https://www.speedscope.app/ and open the .out files which will show you the flame graph.
Try it out, it’s super easy.