counter.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. count int64 //Due to a bug in golang the 64bit variable need to come first to be 64bit aligned. https://golang.org/pkg/sync/atomic/#pkg-note-BUG
  27. *MetricMeta
  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. }