From e31f5ed26eb596e97931db2c231615b04965f53b Mon Sep 17 00:00:00 2001 From: Dmitry Maluka Date: Mon, 30 Jan 2023 03:10:57 +0100 Subject: [PATCH] Add -profile flag for CPU profiling (#2715) There is already a commented-out code in main() for enabling CPU profiling of micro, which is often useful. Adjust it to allow enabling it just by providing -profile flag on the command line, without modifying and recompiling the code. --- cmd/micro/micro.go | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/cmd/micro/micro.go b/cmd/micro/micro.go index e0590244..0c8e428b 100644 --- a/cmd/micro/micro.go +++ b/cmd/micro/micro.go @@ -9,6 +9,7 @@ import ( "os/signal" "regexp" "runtime" + "runtime/pprof" "sort" "strconv" "syscall" @@ -37,6 +38,7 @@ var ( flagConfigDir = flag.String("config-dir", "", "Specify a custom location for the configuration directory") flagOptions = flag.Bool("options", false, "Show all option help") flagDebug = flag.Bool("debug", false, "Enable debug mode (prints debug info to ./log.txt)") + flagProfile = flag.Bool("profile", false, "Enable CPU profiling (writes profile info to ./micro.prof)") flagPlugin = flag.String("plugin", "", "Plugin command") flagClean = flag.Bool("clean", false, "Clean configuration directory") optionFlags map[string]*string @@ -59,6 +61,9 @@ func InitFlags() { fmt.Println(" \tShow all option help") fmt.Println("-debug") fmt.Println(" \tEnable debug mode (enables logging to ./log.txt)") + fmt.Println("-profile") + fmt.Println(" \tEnable CPU profiling (writes profile info to ./micro.prof") + fmt.Println(" \tso it can be analyzed later with \"go tool pprof micro.prof\")") fmt.Println("-version") fmt.Println(" \tShow the version number and information") @@ -228,15 +233,21 @@ func main() { os.Exit(0) }() - // runtime.SetCPUProfileRate(400) - // f, _ := os.Create("micro.prof") - // pprof.StartCPUProfile(f) - // defer pprof.StopCPUProfile() - var err error InitFlags() + if *flagProfile { + f, err := os.Create("micro.prof") + if err != nil { + log.Fatal("error creating CPU profile: ", err) + } + if err := pprof.StartCPUProfile(f); err != nil { + log.Fatal("error starting CPU profile: ", err) + } + defer pprof.StopCPUProfile() + } + InitLog() err = config.InitConfigDir(*flagConfigDir)