github.com/blend/go-sdk@v1.20220411.3/statsd/_bench/main.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package main
     9  
    10  import (
    11  	"flag"
    12  	"fmt"
    13  	"log"
    14  	"runtime"
    15  	"sync"
    16  	"sync/atomic"
    17  	"time"
    18  
    19  	"github.com/blend/go-sdk/statsd"
    20  )
    21  
    22  var (
    23  	addr        = flag.String("addr", "127.0.0.1:8125", "The statsd server address")
    24  	dialTimeout = flag.Duration("dial-timeout", time.Second, "The client dial timeout")
    25  	bufferSize  = flag.Int("buffer-size", 64, "The client buffer size")
    26  	workers     = flag.Int("workers", runtime.NumCPU(), "The number of workers to use")
    27  )
    28  
    29  var metrics = []statsd.Metric{
    30  	{Type: statsd.MetricTypeCount, Name: "http.request", Value: "1", Tags: []string{statsd.Tag("env", "test")}},
    31  	{Type: statsd.MetricTypeCount, Name: "error", Value: "1", Tags: []string{statsd.Tag("env", "test")}},
    32  	{Type: statsd.MetricTypeCount, Name: "http.response", Value: "1", Tags: []string{statsd.Tag("env", "test"), statsd.Tag("status_code", "200")}},
    33  	{Type: statsd.MetricTypeTimer, Name: "http.response.elapsed", Value: "500.0", Tags: []string{statsd.Tag("env", "test"), statsd.Tag("status_code", "200")}},
    34  }
    35  
    36  func main() {
    37  	c, err := statsd.New(
    38  		statsd.OptAddr(*addr),
    39  		statsd.OptDialTimeout(*dialTimeout),
    40  		statsd.OptMaxBufferSize(*bufferSize),
    41  	)
    42  	if err != nil {
    43  		log.Fatal(err)
    44  	}
    45  	wg := sync.WaitGroup{}
    46  	wg.Add(*workers)
    47  	started := time.Now()
    48  	var sent int32
    49  	for workerID := 0; workerID < *workers; workerID++ {
    50  		go func(id int) {
    51  			defer wg.Done()
    52  			var err error
    53  			for x := 0; x < 1024; x++ {
    54  				for _, m := range metrics {
    55  					switch m.Type {
    56  					case statsd.MetricTypeCount:
    57  						v, _ := m.Int64()
    58  						err = c.Count(m.Name, v, m.Tags...)
    59  					case statsd.MetricTypeGauge:
    60  						v, _ := m.Float64()
    61  						err = c.Gauge(m.Name, v, m.Tags...)
    62  					case statsd.MetricTypeTimer:
    63  						v, _ := m.Duration()
    64  						err = c.TimeInMilliseconds(m.Name, v, m.Tags...)
    65  					}
    66  					if err != nil {
    67  						log.Printf("client error: %v\n", err)
    68  					}
    69  					atomic.AddInt32(&sent, 1)
    70  				}
    71  			}
    72  		}(workerID)
    73  	}
    74  	wg.Wait()
    75  
    76  	elapsed := time.Since(started)
    77  	fmt.Printf("sent %d messages in %v (%0.2f m/sec)\n", sent, elapsed, float64(sent)/(float64(elapsed)/float64(time.Second)))
    78  }