github.com/grafana/pyroscope-go/godeltaprof@v0.1.8-0.20240513050943-1b1f97373e2a/example/main.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"net/http"
     7  	_ "net/http/pprof"
     8  	"runtime"
     9  	"sync"
    10  	"time"
    11  
    12  	"github.com/grafana/pyroscope-go/godeltaprof"
    13  	_ "github.com/grafana/pyroscope-go/godeltaprof/http/pprof"
    14  )
    15  
    16  //go:noinline
    17  func work(n int) {
    18  	// revive:disable:empty-block this is fine because this is a example app, not real production code
    19  	for i := 0; i < n; i++ {
    20  	}
    21  	fmt.Printf("work\n")
    22  	// revive:enable:empty-block
    23  }
    24  
    25  var m sync.Mutex
    26  
    27  func fastFunction(wg *sync.WaitGroup) {
    28  	m.Lock()
    29  	defer m.Unlock()
    30  
    31  	work(200000000)
    32  
    33  	wg.Done()
    34  }
    35  
    36  func slowFunction(wg *sync.WaitGroup) {
    37  	m.Lock()
    38  	defer m.Unlock()
    39  
    40  	work(800000000)
    41  	wg.Done()
    42  }
    43  
    44  func main() {
    45  	go func() {
    46  		err := http.ListenAndServe("localhost:6060", http.DefaultServeMux)
    47  		if err != nil {
    48  			panic(err)
    49  		}
    50  	}()
    51  	go func() {
    52  		deltaHeapProfiler := godeltaprof.NewHeapProfiler()
    53  		deltaBlockProfiler := godeltaprof.NewBlockProfiler()
    54  		deltaMutexProfiler := godeltaprof.NewMutexProfiler()
    55  		for {
    56  			time.Sleep(10 * time.Second)
    57  			deltaHeapProfiler.Profile(bytes.NewBuffer(nil))
    58  			deltaBlockProfiler.Profile(bytes.NewBuffer(nil))
    59  			deltaMutexProfiler.Profile(bytes.NewBuffer(nil))
    60  		}
    61  	}()
    62  	runtime.SetMutexProfileFraction(5)
    63  	runtime.SetBlockProfileRate(5)
    64  
    65  	for {
    66  		wg := sync.WaitGroup{}
    67  		wg.Add(2)
    68  		go fastFunction(&wg)
    69  		go slowFunction(&wg)
    70  		wg.Wait()
    71  	}
    72  }