timer.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package metrics
  2. import (
  3. "time"
  4. "github.com/prometheus/client_golang/prometheus"
  5. )
  6. // Timer assumes the metrics is partitioned by one label
  7. type Timer struct {
  8. startTime map[string]time.Time
  9. metrics *prometheus.HistogramVec
  10. measureUnit time.Duration
  11. labelKey string
  12. }
  13. func NewTimer(metrics *prometheus.HistogramVec, unit time.Duration, labelKey string) *Timer {
  14. return &Timer{
  15. startTime: make(map[string]time.Time),
  16. measureUnit: unit,
  17. metrics: metrics,
  18. labelKey: labelKey,
  19. }
  20. }
  21. func (i *Timer) Start(labelVal string) {
  22. i.startTime[labelVal] = time.Now()
  23. }
  24. func (i *Timer) End(labelVal string) time.Duration {
  25. if start, ok := i.startTime[labelVal]; ok {
  26. return Latency(start, time.Now())
  27. }
  28. return 0
  29. }
  30. func (i *Timer) Observe(measurement time.Duration, labelVal string) {
  31. metricsLabels := prometheus.Labels{i.labelKey: labelVal}
  32. i.metrics.With(metricsLabels).Observe(float64(measurement / i.measureUnit))
  33. }
  34. func (i *Timer) EndAndObserve(labelVal string) {
  35. i.Observe(i.End(labelVal), labelVal)
  36. }
  37. func Latency(startTime, endTime time.Time) time.Duration {
  38. return endTime.Sub(startTime)
  39. }