Last active
July 19, 2024 19:14
-
-
Save dlisboa/bd4193afd8a258e51d03d7fe276d3fb8 to your computer and use it in GitHub Desktop.
pprof_example.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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