github.com/bir3/gocompiler@v0.3.205/src/cmd/compile/internal/gc/util.go (about) 1 // Copyright 2015 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package gc 6 7 import ( 8 "os" 9 "runtime" 10 "runtime/pprof" 11 tracepkg "runtime/trace" 12 13 "github.com/bir3/gocompiler/src/cmd/compile/internal/base" 14 ) 15 16 func startProfile() { 17 if base.Flag.CPUProfile != "" { 18 f, err := os.Create(base.Flag.CPUProfile) 19 if err != nil { 20 base.Fatalf("%v", err) 21 } 22 if err := pprof.StartCPUProfile(f); err != nil { 23 base.Fatalf("%v", err) 24 } 25 base.AtExit(pprof.StopCPUProfile) 26 } 27 if base.Flag.MemProfile != "" { 28 if base.Flag.MemProfileRate != 0 { 29 runtime.MemProfileRate = base.Flag.MemProfileRate 30 } 31 f, err := os.Create(base.Flag.MemProfile) 32 if err != nil { 33 base.Fatalf("%v", err) 34 } 35 base.AtExit(func() { 36 // Profile all outstanding allocations. 37 runtime.GC() 38 // compilebench parses the memory profile to extract memstats, 39 // which are only written in the legacy pprof format. 40 // See golang.org/issue/18641 and runtime/pprof/pprof.go:writeHeap. 41 const writeLegacyFormat = 1 42 if err := pprof.Lookup("heap").WriteTo(f, writeLegacyFormat); err != nil { 43 base.Fatalf("%v", err) 44 } 45 }) 46 } else { 47 // Not doing memory profiling; disable it entirely. 48 runtime.MemProfileRate = 0 49 } 50 if base.Flag.BlockProfile != "" { 51 f, err := os.Create(base.Flag.BlockProfile) 52 if err != nil { 53 base.Fatalf("%v", err) 54 } 55 runtime.SetBlockProfileRate(1) 56 base.AtExit(func() { 57 pprof.Lookup("block").WriteTo(f, 0) 58 f.Close() 59 }) 60 } 61 if base.Flag.MutexProfile != "" { 62 f, err := os.Create(base.Flag.MutexProfile) 63 if err != nil { 64 base.Fatalf("%v", err) 65 } 66 runtime.SetMutexProfileFraction(1) 67 base.AtExit(func() { 68 pprof.Lookup("mutex").WriteTo(f, 0) 69 f.Close() 70 }) 71 } 72 if base.Flag.TraceProfile != "" { 73 f, err := os.Create(base.Flag.TraceProfile) 74 if err != nil { 75 base.Fatalf("%v", err) 76 } 77 if err := tracepkg.Start(f); err != nil { 78 base.Fatalf("%v", err) 79 } 80 base.AtExit(tracepkg.Stop) 81 } 82 }