From 3f1c66813cdea59629bef4c4440ac65409ca8a54 Mon Sep 17 00:00:00 2001 From: Parnic Date: Tue, 12 Jul 2022 08:44:46 -0500 Subject: [PATCH] Add support for cpu and memory profiling My day 18 was slow and I wasn't completely certain where it was all coming from, so I dove into Go's profiling stuff. It was super helpful in identifying the problem and giving me easy wins that took runtime from 4.6s/14.4s (part 1/part 2) to 180ms/50ms just from swapping some arrays for maps, which the profile pointed out very clearly. --- .gitignore | 1 + main.go | 27 ++++++++++++++++++++++++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index e381e30..08ca6b2 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ __debug_bin aoc2019 debug.test +*.*prof diff --git a/main.go b/main.go index af9ca68..a379c8d 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ import ( "fmt" "log" "os" + "runtime/pprof" "strconv" "strings" "time" @@ -26,8 +27,10 @@ const ( ) var ( - flagPart1 = flag.Bool("part1", false, "whether to run part1 or not; if no flags are present, all parts are run") - flagPart2 = flag.Bool("part2", false, "whether to run part2 or not; if no flags are present, all parts are run") + flagPart1 = flag.Bool("part1", false, "whether to run part1 or not; if no flags are present, all parts are run") + flagPart2 = flag.Bool("part2", false, "whether to run part2 or not; if no flags are present, all parts are run") + flagCpuProfile = flag.String("cpuprofile", "", "write cpu profile to file") + flagMemProfile = flag.String("memprofile", "", "write memory profile to file") ) var dayMap = []day{ @@ -53,6 +56,17 @@ var dayMap = []day{ func main() { flag.Parse() + if *flagCpuProfile != "" { + f, err := os.Create(*flagCpuProfile) + if err != nil { + log.Fatal(err) + } + defer f.Close() + + pprof.StartCPUProfile(f) + defer pprof.StopCPUProfile() + } + arg := strconv.Itoa(len(dayMap)) flagArgs := flag.Args() if len(flagArgs) > 0 && len(flagArgs[0]) > 0 { @@ -77,7 +91,14 @@ func main() { solve(dayMap[iArg-1]) } - os.Exit(0) + if *flagMemProfile != "" { + f, err := os.Create(*flagMemProfile) + if err != nil { + log.Fatal(err) + } + pprof.WriteHeapProfile(f) + f.Close() + } } func solve(d day) {