Add CPU/Memory profiling flags

This commit is contained in:
2024-02-13 10:44:42 -06:00
parent e6283aefae
commit 85a3696631
2 changed files with 36 additions and 1 deletions
Vendored
+2 -1
View File
@@ -4,4 +4,5 @@ banner
.*.go .*.go
dumps/ dumps/
js/ js/
.vscode/ .vscode/
*.prof
+34
View File
@@ -2,11 +2,15 @@ package main
import ( import (
"context" "context"
"flag"
"fmt" "fmt"
"net/http" "net/http"
"net/http/cookiejar" "net/http/cookiejar"
_ "net/http/pprof"
"os" "os"
"os/signal" "os/signal"
"runtime"
"runtime/pprof"
"syscall" "syscall"
"time" "time"
_ "time/tzdata" _ "time/tzdata"
@@ -31,6 +35,8 @@ var (
environment string environment string
CentralTimeLocation *time.Location CentralTimeLocation *time.Location
isClosing bool = false isClosing bool = false
cpuProfile = flag.String("cpuprofile", "", "write cpu profile to `file`")
memoryProfile = flag.String("memprofile", "", "write memory profile to `file`")
) )
const ( const (
@@ -129,6 +135,21 @@ func initRedis() {
} }
func main() { func main() {
flag.Parse()
// CPU Profiling (if requested)
if *cpuProfile != "" {
f, err := os.Create(*cpuProfile)
if err != nil {
log.Fatal().Stack().Err(err).Msg("could not create CPU profile")
}
defer f.Close() // error handling omitted for example
if err := pprof.StartCPUProfile(f); err != nil {
log.Fatal().Stack().Err(err).Msg("could not start CPU profile")
}
defer pprof.StopCPUProfile()
}
initRedis() initRedis()
// Create cookie jar // Create cookie jar
@@ -303,6 +324,19 @@ func main() {
isClosing = true isClosing = true
// Write memory profile if requested
if *memoryProfile != "" {
f, err := os.Create(*memoryProfile)
if err != nil {
log.Fatal().Stack().Err(err).Msg("could not create memory profile")
}
defer f.Close() // error handling omitted for example
runtime.GC() // get up-to-date statistics
if err := pprof.WriteHeapProfile(f); err != nil {
log.Fatal().Stack().Err(err).Msg("could not write memory profile")
}
}
// Defers are called after this // Defers are called after this
log.Warn().Str("signal", closingSignal.String()).Msg("Gracefully shutting down") log.Warn().Str("signal", closingSignal.String()).Msg("Gracefully shutting down")
} }