counter.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package metrics
  2. import "sync/atomic"
  3. // Counters hold an int64 value that can be incremented and decremented.
  4. //
  5. // This is an interface so as to encourage other structs to implement
  6. // the Counter API as appropriate.
  7. type Counter interface {
  8. Clear()
  9. Count() int64
  10. Dec(int64)
  11. Inc(int64)
  12. }
  13. // Get an existing or create and register a new Counter.
  14. func GetOrRegisterCounter(name string, r Registry) Counter {
  15. if nil == r {
  16. r = DefaultRegistry
  17. }
  18. return r.GetOrRegister(name, NewCounter()).(Counter)
  19. }
  20. // Create a new Counter.
  21. func NewCounter() Counter {
  22. if UseNilMetrics {
  23. return NilCounter{}
  24. }
  25. return &StandardCounter{0}
  26. }
  27. // Create and register a new Counter.
  28. func NewRegisteredCounter(name string, r Registry) Counter {
  29. c := NewCounter()
  30. if nil == r {
  31. r = DefaultRegistry
  32. }
  33. r.Register(name, c)
  34. return c
  35. }
  36. // No-op Counter.
  37. type NilCounter struct{}
  38. // No-op.
  39. func (c NilCounter) Clear() {}
  40. // No-op.
  41. func (c NilCounter) Count() int64 { return 0 }
  42. // No-op.
  43. func (c NilCounter) Dec(i int64) {}
  44. // No-op.
  45. func (c NilCounter) Inc(i int64) {}
  46. // The standard implementation of a Counter uses the sync/atomic package
  47. // to manage a single int64 value.
  48. type StandardCounter struct {
  49. count int64
  50. }
  51. // Clear the counter: set it to zero.
  52. func (c *StandardCounter) Clear() {
  53. atomic.StoreInt64(&c.count, 0)
  54. }
  55. // Return the current count.
  56. func (c *StandardCounter) Count() int64 {
  57. return atomic.LoadInt64(&c.count)
  58. }
  59. // Decrement the counter by the given amount.
  60. func (c *StandardCounter) Dec(i int64) {
  61. atomic.AddInt64(&c.count, -i)
  62. }
  63. // Increment the counter by the given amount.
  64. func (c *StandardCounter) Inc(i int64) {
  65. atomic.AddInt64(&c.count, i)
  66. }