gitee.com/sasukebo/go-micro/v4@v4.7.1/debug/profile/pprof/pprof.go (about) 1 // Package pprof provides a pprof profiler 2 package pprof 3 4 import ( 5 "os" 6 "path/filepath" 7 "runtime" 8 "runtime/pprof" 9 "sync" 10 11 "gitee.com/sasukebo/go-micro/v4/debug/profile" 12 ) 13 14 type profiler struct { 15 opts profile.Options 16 17 sync.Mutex 18 running bool 19 20 // where the cpu profile is written 21 cpuFile *os.File 22 // where the mem profile is written 23 memFile *os.File 24 } 25 26 func (p *profiler) Start() error { 27 p.Lock() 28 defer p.Unlock() 29 30 if p.running { 31 return nil 32 } 33 34 cpuFile := filepath.Join(os.TempDir(), "cpu.pprof") 35 memFile := filepath.Join(os.TempDir(), "mem.pprof") 36 37 if len(p.opts.Name) > 0 { 38 cpuFile = filepath.Join(os.TempDir(), p.opts.Name+".cpu.pprof") 39 memFile = filepath.Join(os.TempDir(), p.opts.Name+".mem.pprof") 40 } 41 42 f1, err := os.Create(cpuFile) 43 if err != nil { 44 return err 45 } 46 47 f2, err := os.Create(memFile) 48 if err != nil { 49 return err 50 } 51 52 // start cpu profiling 53 if err := pprof.StartCPUProfile(f1); err != nil { 54 return err 55 } 56 57 // set cpu file 58 p.cpuFile = f1 59 // set mem file 60 p.memFile = f2 61 62 p.running = true 63 64 return nil 65 } 66 67 func (p *profiler) Stop() error { 68 p.Lock() 69 defer p.Unlock() 70 71 if !p.running { 72 return nil 73 } 74 75 pprof.StopCPUProfile() 76 p.cpuFile.Close() 77 runtime.GC() 78 pprof.WriteHeapProfile(p.memFile) 79 p.memFile.Close() 80 p.running = false 81 p.cpuFile = nil 82 p.memFile = nil 83 return nil 84 } 85 86 func (p *profiler) String() string { 87 return "pprof" 88 } 89 90 func NewProfile(opts ...profile.Option) profile.Profile { 91 var options profile.Options 92 for _, o := range opts { 93 o(&options) 94 } 95 p := new(profiler) 96 p.opts = options 97 return p 98 }