@@ -18,6 +18,8 @@ import (
1818 "fmt"
1919 "log/slog"
2020 "os"
21+ "runtime/pprof"
22+ "strings"
2123
2224 "github.com/blinklabs-io/dingo/internal/config"
2325 "github.com/blinklabs-io/dingo/internal/version"
@@ -37,7 +39,9 @@ func slogPrintf(format string, v ...any) {
3739
3840var (
3941 globalFlags = struct {
40- debug bool
42+ cpuprofile string
43+ memprofile string
44+ debug bool
4145 }{}
4246 configFile string
4347)
@@ -72,6 +76,37 @@ func commonRun() *slog.Logger {
7276}
7377
7478func main () {
79+ // Parse profiling flags before cobra setup
80+ cpuprofile := ""
81+ memprofile := ""
82+ for _ , arg := range os .Args {
83+ if after , ok := strings .CutPrefix (arg , "--cpuprofile=" ); ok {
84+ cpuprofile = after
85+ }
86+ if after , ok := strings .CutPrefix (arg , "--memprofile=" ); ok {
87+ memprofile = after
88+ }
89+ }
90+
91+ // Initialize CPU profiling (starts immediately, stops on exit)
92+ if cpuprofile != "" {
93+ fmt .Fprintf (os .Stderr , "Starting CPU profiling to %s\n " , cpuprofile )
94+ f , err := os .Create (cpuprofile )
95+ if err != nil {
96+ fmt .Fprintf (os .Stderr , "could not create CPU profile: %v\n " , err )
97+ os .Exit (1 )
98+ }
99+ defer f .Close ()
100+ if err := pprof .StartCPUProfile (f ); err != nil {
101+ fmt .Fprintf (os .Stderr , "could not start CPU profile: %v\n " , err )
102+ os .Exit (1 )
103+ }
104+ defer func () {
105+ pprof .StopCPUProfile ()
106+ fmt .Fprintf (os .Stderr , "CPU profiling stopped\n " )
107+ }()
108+ }
109+
75110 rootCmd := & cobra.Command {
76111 Use : programName ,
77112 Run : func (cmd * cobra.Command , args []string ) {
@@ -89,6 +124,10 @@ func main() {
89124 BoolVarP (& globalFlags .debug , "debug" , "D" , false , "enable debug logging" )
90125 rootCmd .PersistentFlags ().
91126 StringVar (& configFile , "config" , "" , "path to config file" )
127+ rootCmd .PersistentFlags ().
128+ StringVar (& globalFlags .cpuprofile , "cpuprofile" , "" , "write cpu profile to file" )
129+ rootCmd .PersistentFlags ().
130+ StringVar (& globalFlags .memprofile , "memprofile" , "" , "write memory profile to file" )
92131
93132 rootCmd .PersistentPreRunE = func (cmd * cobra.Command , args []string ) error {
94133 cfg , err := config .LoadConfig (configFile )
@@ -109,4 +148,19 @@ func main() {
109148 // NOTE: we purposely don't display the error, since cobra will have already displayed it
110149 os .Exit (1 )
111150 }
151+
152+ // Finalize memory profiling (captures heap state at program end)
153+ if memprofile != "" {
154+ f , err := os .Create (memprofile )
155+ if err != nil {
156+ fmt .Fprintf (os .Stderr , "could not create memory profile: %v\n " , err )
157+ os .Exit (1 )
158+ }
159+ defer f .Close ()
160+ if err := pprof .WriteHeapProfile (f ); err != nil {
161+ fmt .Fprintf (os .Stderr , "could not write memory profile: %v\n " , err )
162+ os .Exit (1 )
163+ }
164+ fmt .Fprintf (os .Stderr , "Memory profiling complete\n " )
165+ }
112166}
0 commit comments