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-06-18 22:53:56 -05:00
parent 4b5bd0d4e0
commit 3d3ea6e266
2 changed files with 25 additions and 3 deletions

1
.gitignore vendored
View File

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

27
main.go
View File

@ -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) {