Skip to content

Instantly share code, notes, and snippets.

@wader
Created August 29, 2021 22:25
Show Gist options
  • Save wader/87b034dbc986b4d50c8ad5f41c39d2b7 to your computer and use it in GitHub Desktop.
Save wader/87b034dbc986b4d50c8ad5f41c39d2b7 to your computer and use it in GitHub Desktop.
pprof
package cli
import (
"log"
"os"
"runtime"
"runtime/pprof"
)
func maybeProfile() func() {
return profile(os.Getenv("CPUPROFILE"), os.Getenv("MEMPROFILE"))
}
func profile(cpuProfilePath string, memProfilePath string) func() {
var deferFns []func()
if cpuProfilePath != "" {
f, err := os.Create(cpuProfilePath)
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)
} else {
deferFns = append(deferFns, func() {
pprof.StopCPUProfile()
if err := f.Close(); err != nil {
log.Fatal("could not close CPU profile: ", err)
}
})
}
}
return func() {
for _, fn := range deferFns {
fn()
}
if memProfilePath != "" {
f, err := os.Create(memProfilePath)
if err != nil {
log.Fatal("could not create memory profile: ", err)
}
if err := pprof.WriteHeapProfile(f); err != nil {
log.Fatal("could not write memory profile: ", err)
} else {
runtime.GC() // get up-to-date statistics
if err := f.Close(); err != nil {
log.Fatal("could not close memory profile: ", err)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment