github.com/status-im/status-go@v1.1.0/profiling/cpu.go (about)

     1  package profiling
     2  
     3  import (
     4  	"errors"
     5  	"os"
     6  	"path/filepath"
     7  	"runtime/pprof"
     8  )
     9  
    10  // CPUFilename is a filename in which the CPU profiling is stored.
    11  const CPUFilename = "status_cpu.prof"
    12  
    13  var cpuFile *os.File
    14  
    15  // StartCPUProfile enables CPU profiling for the current process. While profiling,
    16  // the profile will be buffered and written to the file in folder dataDir.
    17  func StartCPUProfile(dataDir string) error {
    18  	if cpuFile != nil {
    19  		return errors.New("cpu profiling is already started")
    20  	}
    21  
    22  	var err error
    23  	cpuFile, err = os.Create(filepath.Join(dataDir, CPUFilename))
    24  	if err != nil {
    25  		return err
    26  	}
    27  
    28  	return pprof.StartCPUProfile(cpuFile)
    29  }
    30  
    31  // StopCPUProfile stops the current CPU profile, if any, and closes the file.
    32  func StopCPUProfile() error {
    33  	if cpuFile == nil {
    34  		return nil
    35  	}
    36  	pprof.StopCPUProfile()
    37  	err := cpuFile.Close()
    38  	cpuFile = nil
    39  	return err
    40  }