github.com/msales/pkg/v3@v3.24.0/stats/timer.go (about)

     1  package stats
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  )
     7  
     8  // Timer represents a timer.
     9  type Timer interface {
    10  	// Start starts the timer.
    11  	Start()
    12  	// Done stops the timer and submits the Timing metric.
    13  	Done()
    14  }
    15  
    16  type timer struct {
    17  	start time.Time
    18  	ctx   context.Context
    19  	name  string
    20  	rate  float32
    21  	tags  []interface{}
    22  }
    23  
    24  // Time is a shorthand for Timing.
    25  func Time(ctx context.Context, name string, rate float32, tags ...interface{}) Timer {
    26  	t := &timer{ctx: ctx, name: name, rate: rate, tags: tags}
    27  	t.Start()
    28  	return t
    29  }
    30  
    31  func (t *timer) Start() {
    32  	t.start = time.Now()
    33  }
    34  
    35  func (t *timer) Done() {
    36  	Timing(t.ctx, t.name, time.Since(t.start), t.rate, t.tags...)
    37  }