github.com/peggyl/go@v0.0.0-20151008231540-ae315999c2d5/src/cmd/compile/internal/gc/util.go (about)

     1  package gc
     2  
     3  import (
     4  	"os"
     5  	"runtime"
     6  	"runtime/pprof"
     7  	"strconv"
     8  )
     9  
    10  func (n *Node) Line() string {
    11  	return Ctxt.LineHist.LineString(int(n.Lineno))
    12  }
    13  
    14  func atoi(s string) int {
    15  	// NOTE: Not strconv.Atoi, accepts hex and octal prefixes.
    16  	n, _ := strconv.ParseInt(s, 0, 0)
    17  	return int(n)
    18  }
    19  
    20  var atExitFuncs []func()
    21  
    22  func AtExit(f func()) {
    23  	atExitFuncs = append(atExitFuncs, f)
    24  }
    25  
    26  func Exit(code int) {
    27  	for i := len(atExitFuncs) - 1; i >= 0; i-- {
    28  		f := atExitFuncs[i]
    29  		atExitFuncs = atExitFuncs[:i]
    30  		f()
    31  	}
    32  	os.Exit(code)
    33  }
    34  
    35  var (
    36  	cpuprofile     string
    37  	memprofile     string
    38  	memprofilerate int64
    39  )
    40  
    41  func startProfile() {
    42  	if cpuprofile != "" {
    43  		f, err := os.Create(cpuprofile)
    44  		if err != nil {
    45  			Fatalf("%v", err)
    46  		}
    47  		if err := pprof.StartCPUProfile(f); err != nil {
    48  			Fatalf("%v", err)
    49  		}
    50  		AtExit(pprof.StopCPUProfile)
    51  	}
    52  	if memprofile != "" {
    53  		if memprofilerate != 0 {
    54  			runtime.MemProfileRate = int(memprofilerate)
    55  		}
    56  		f, err := os.Create(memprofile)
    57  		if err != nil {
    58  			Fatalf("%v", err)
    59  		}
    60  		AtExit(func() {
    61  			runtime.GC() // profile all outstanding allocations
    62  			if err := pprof.WriteHeapProfile(f); err != nil {
    63  				Fatalf("%v", err)
    64  			}
    65  		})
    66  	}
    67  }