github.com/ActiveState/cli@v0.0.0-20240508170324-6801f60cd051/internal/profile/profile.go (about) 1 package profile 2 3 import ( 4 "fmt" 5 "os" 6 "strings" 7 "time" 8 9 "github.com/ActiveState/cli/internal/constants" 10 "github.com/ActiveState/cli/internal/logging" 11 "github.com/felixge/fgprof" 12 13 "github.com/ActiveState/cli/internal/errs" 14 ) 15 16 var profilingEnabled = false 17 18 func init() { 19 profilingEnabled = os.Getenv(constants.ProfileEnvVarName) == "true" 20 } 21 22 // CPU runs the CPU profiler. Be sure to run the cleanup func. 23 func CPU() (cleanUp func() error, err error) { 24 timeString := time.Now().Format("20060102-150405.000") 25 timeString = strings.Replace(timeString, ".", "-", 1) 26 cpuProfFile := fmt.Sprintf("cpu_%s.prof", timeString) 27 28 f, err := os.Create(cpuProfFile) 29 if err != nil { 30 return func() error { return nil }, errs.Wrap(err, "Could not create CPU profiling file: %s", cpuProfFile) 31 } 32 33 return fgprof.Start(f, fgprof.FormatPprof), nil 34 } 35 36 func Measure(name string, start time.Time) { 37 if profilingEnabled { 38 msg := fmt.Sprintf("Profiling: %s took %s (%d)\n", name, time.Since(start), time.Since(start).Milliseconds()) 39 logging.Debug(msg) 40 fmt.Print(msg) 41 } 42 }