Black Lives Matter. Support the Equal Justice Initiative.

Source file src/cmd/compile/internal/gc/util.go

Documentation: cmd/compile/internal/gc

     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  
    12  	"cmd/compile/internal/base"
    13  )
    14  
    15  var (
    16  	memprofilerate int64
    17  	traceHandler   func(string)
    18  )
    19  
    20  func startProfile() {
    21  	if base.Flag.CPUProfile != "" {
    22  		f, err := os.Create(base.Flag.CPUProfile)
    23  		if err != nil {
    24  			base.Fatalf("%v", err)
    25  		}
    26  		if err := pprof.StartCPUProfile(f); err != nil {
    27  			base.Fatalf("%v", err)
    28  		}
    29  		base.AtExit(pprof.StopCPUProfile)
    30  	}
    31  	if base.Flag.MemProfile != "" {
    32  		if memprofilerate != 0 {
    33  			runtime.MemProfileRate = int(memprofilerate)
    34  		}
    35  		f, err := os.Create(base.Flag.MemProfile)
    36  		if err != nil {
    37  			base.Fatalf("%v", err)
    38  		}
    39  		base.AtExit(func() {
    40  			// Profile all outstanding allocations.
    41  			runtime.GC()
    42  			// compilebench parses the memory profile to extract memstats,
    43  			// which are only written in the legacy pprof format.
    44  			// See golang.org/issue/18641 and runtime/pprof/pprof.go:writeHeap.
    45  			const writeLegacyFormat = 1
    46  			if err := pprof.Lookup("heap").WriteTo(f, writeLegacyFormat); err != nil {
    47  				base.Fatalf("%v", err)
    48  			}
    49  		})
    50  	} else {
    51  		// Not doing memory profiling; disable it entirely.
    52  		runtime.MemProfileRate = 0
    53  	}
    54  	if base.Flag.BlockProfile != "" {
    55  		f, err := os.Create(base.Flag.BlockProfile)
    56  		if err != nil {
    57  			base.Fatalf("%v", err)
    58  		}
    59  		runtime.SetBlockProfileRate(1)
    60  		base.AtExit(func() {
    61  			pprof.Lookup("block").WriteTo(f, 0)
    62  			f.Close()
    63  		})
    64  	}
    65  	if base.Flag.MutexProfile != "" {
    66  		f, err := os.Create(base.Flag.MutexProfile)
    67  		if err != nil {
    68  			base.Fatalf("%v", err)
    69  		}
    70  		startMutexProfiling()
    71  		base.AtExit(func() {
    72  			pprof.Lookup("mutex").WriteTo(f, 0)
    73  			f.Close()
    74  		})
    75  	}
    76  	if base.Flag.TraceProfile != "" && traceHandler != nil {
    77  		traceHandler(base.Flag.TraceProfile)
    78  	}
    79  }
    80  

View as plain text