Skip to content

Instantly share code, notes, and snippets.

@dlisboa
Last active July 19, 2024 19:14
Show Gist options
  • Save dlisboa/bd4193afd8a258e51d03d7fe276d3fb8 to your computer and use it in GitHub Desktop.
Save dlisboa/bd4193afd8a258e51d03d7fe276d3fb8 to your computer and use it in GitHub Desktop.
pprof_example.go
package main
import (
"flag"
"log"
"os"
"runtime/pprof"
)
var (
cpuprofile = flag.String("cpuprofile", "", "write cpu profile to this file")
memprofile = flag.String("memprofile", "", "write memory profile to this file")
)
func main() {
flag.Parse()
if *cpuprofile != "" {
cpuf, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(cpuf)
defer cpuf.Close()
defer pprof.StopCPUProfile()
}
// some code
var ints []int
sum := 0
for i := range 1_000_000 {
ints = append(ints, i)
sum += i
}
// snapshot mem
if *memprofile != "" {
memf, err := os.Create(*memprofile)
if err != nil {
log.Fatal(err)
}
pprof.WriteHeapProfile(memf)
memf.Close()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment