Skip to content

Instantly share code, notes, and snippets.

@rfong
Last active May 4, 2018 18:31
Show Gist options
  • Save rfong/82cd1c9bc3417b3f1b66c853509ad50a to your computer and use it in GitHub Desktop.
Save rfong/82cd1c9bc3417b3f1b66c853509ad50a to your computer and use it in GitHub Desktop.
golang pprof example
// Example:
// go test <options> -cpuprofile cpu.prof -memprofile mem.prof ./...
// go tool pprof # Interactive console
// go tool pprof -http=localhost:6060 cpu.prof # Visualization
import (
"flag"
"log"
"runtime"
"runtime/pprof"
)
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`")
var memprofile = flag.String("memprofile", "", "write memory profile to `file`")
// pprof if -cpuprofile
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal("could not create CPU profile: ", err)
}
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatal("could not start CPU profile: ", err)
}
defer pprof.StopCPUProfile()
}
// <something to profile>
// pprof if -memprofile
if *memprofile != "" {
f, err := os.Create(*memprofile)
if err != nil {
log.Fatal("could not create memory profile: ", err)
}
runtime.GC() // get up-to-date statistics
if err := pprof.WriteHeapProfile(f); err != nil {
log.Fatal("could not write memory profile: ", err)
}
f.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment