github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/examples/golang-pull/file/main.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"log"
     6  	"net/http"
     7  	_ "net/http/pprof"
     8  	"os"
     9  	"runtime"
    10  	"runtime/pprof"
    11  	"sync"
    12  
    13  	"github.com/pyroscope-io/client/pyroscope"
    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  	// revive:enable:empty-block
    22  }
    23  
    24  var m *sync.Mutex
    25  
    26  func init() {
    27  	m = &sync.Mutex{}
    28  	runtime.SetMutexProfileFraction(5)
    29  	runtime.SetBlockProfileRate(5)
    30  }
    31  
    32  func fastFunction(c context.Context, wg *sync.WaitGroup) {
    33  	m.Lock()
    34  	defer m.Unlock()
    35  	pyroscope.TagWrapper(c, pyroscope.Labels("function", "fast"), func(c context.Context) {
    36  		work(20000000)
    37  	})
    38  	wg.Done()
    39  }
    40  
    41  func slowFunction(c context.Context, wg *sync.WaitGroup) {
    42  	m.Lock()
    43  	defer m.Unlock()
    44  	// standard pprof.Do wrappers work as well
    45  	pprof.Do(c, pprof.Labels("function", "slow"), func(c context.Context) {
    46  		work(80000000)
    47  	})
    48  	wg.Done()
    49  }
    50  
    51  func main() {
    52  	go func() {
    53  		log.Println(http.ListenAndServe(":6060", nil))
    54  	}()
    55  	serverAddress := os.Getenv("PYROSCOPE_SERVER_ADDRESS")
    56  	if serverAddress == "" {
    57  		serverAddress = "http://localhost:4040"
    58  	}
    59  	pyroscope.TagWrapper(context.Background(), pyroscope.Labels("foo", "bar"), func(c context.Context) {
    60  		for {
    61  			wg := sync.WaitGroup{}
    62  			wg.Add(6)
    63  			go fastFunction(c, &wg)
    64  			go fastFunction(c, &wg)
    65  			go fastFunction(c, &wg)
    66  			go slowFunction(c, &wg)
    67  			go slowFunction(c, &wg)
    68  			go slowFunction(c, &wg)
    69  			wg.Wait()
    70  		}
    71  	})
    72  }