counter.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package metrics
  2. import "sync/atomic"
  3. // Counters hold an int64 value that can be incremented and decremented.
  4. type Counter interface {
  5. Metric
  6. Clear()
  7. Count() int64
  8. Dec(int64)
  9. Inc(int64)
  10. }
  11. // NewCounter constructs a new StandardCounter.
  12. func NewCounter(meta *MetricMeta) Counter {
  13. return &StandardCounter{
  14. MetricMeta: meta,
  15. count: 0,
  16. }
  17. }
  18. func RegCounter(name string, tagStrings ...string) Counter {
  19. cr := NewCounter(NewMetricMeta(name, tagStrings))
  20. MetricStats.Register(cr)
  21. return cr
  22. }
  23. // StandardCounter is the standard implementation of a Counter and uses the
  24. // sync/atomic package to manage a single int64 value.
  25. type StandardCounter struct {
  26. *MetricMeta
  27. count int64
  28. }
  29. // Clear sets the counter to zero.
  30. func (c *StandardCounter) Clear() {
  31. atomic.StoreInt64(&c.count, 0)
  32. }
  33. // Count returns the current count.
  34. func (c *StandardCounter) Count() int64 {
  35. return atomic.LoadInt64(&c.count)
  36. }
  37. // Dec decrements the counter by the given amount.
  38. func (c *StandardCounter) Dec(i int64) {
  39. atomic.AddInt64(&c.count, -i)
  40. }
  41. // Inc increments the counter by the given amount.
  42. func (c *StandardCounter) Inc(i int64) {
  43. atomic.AddInt64(&c.count, i)
  44. }
  45. func (c *StandardCounter) Snapshot() Metric {
  46. return &StandardCounter{
  47. MetricMeta: c.MetricMeta,
  48. count: c.count,
  49. }
  50. }