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

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