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.
This commit is contained in:
2022-07-12 08:44:46 -05:00
parent 1f27585231
commit 3f1c66813c
2 changed files with 25 additions and 3 deletions

1
.gitignore vendored
View File

@ -2,3 +2,4 @@
__debug_bin __debug_bin
aoc2019 aoc2019
debug.test debug.test
*.*prof

23
main.go
View File

@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"log" "log"
"os" "os"
"runtime/pprof"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@ -28,6 +29,8 @@ const (
var ( var (
flagPart1 = flag.Bool("part1", false, "whether to run part1 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") 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{ var dayMap = []day{
@ -53,6 +56,17 @@ var dayMap = []day{
func main() { func main() {
flag.Parse() 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)) arg := strconv.Itoa(len(dayMap))
flagArgs := flag.Args() flagArgs := flag.Args()
if len(flagArgs) > 0 && len(flagArgs[0]) > 0 { if len(flagArgs) > 0 && len(flagArgs[0]) > 0 {
@ -77,7 +91,14 @@ func main() {
solve(dayMap[iArg-1]) 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) { func solve(d day) {