github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/testing/profile.go (about)

     1  package testing
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"os/exec"
     7  	"runtime/pprof"
     8  	"time"
     9  
    10  	"github.com/sirupsen/logrus"
    11  
    12  	"github.com/felixge/fgprof"
    13  )
    14  
    15  func FProfile(name string, cb func()) time.Duration {
    16  	t := time.Now()
    17  	path := "/tmp/profile-" + name + ".folded"
    18  	pathSVG := "/tmp/profile-" + name + ".svg"
    19  	f, err := os.Create(path)
    20  	if err == nil {
    21  		endProfile := fgprof.Start(f, fgprof.FormatFolded)
    22  		defer func() {
    23  			endProfile()
    24  			cmd := fmt.Sprintf("cat '%s' | grep -v gopark | flamegraph.pl > '%s'", path, pathSVG)
    25  			logrus.Debug("cmd", cmd)
    26  			err := exec.Command("sh", "-c", cmd).Run()
    27  			if err != nil {
    28  				panic(err)
    29  			}
    30  		}()
    31  	}
    32  	cb()
    33  	d := time.Since(t)
    34  	return d
    35  }
    36  
    37  func Profile(name string, cb func()) time.Duration {
    38  	t := time.Now()
    39  	cb()
    40  	d := time.Since(t)
    41  	logrus.Debugf("%q took %s", name, d)
    42  	return d
    43  }
    44  
    45  func PProfile(name string, cb func()) time.Duration {
    46  	t := time.Now()
    47  	f, err := os.Create("/tmp/profile-" + name + ".prof")
    48  	if err = pprof.StartCPUProfile(f); err == nil {
    49  		defer pprof.StopCPUProfile()
    50  	}
    51  	cb()
    52  	d := time.Since(t)
    53  	logrus.Debug(name, d)
    54  	return d
    55  }