counter.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2017 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package metric
  15. import (
  16. "sync/atomic"
  17. )
  18. type Counter interface {
  19. Count() int64
  20. Inc(int64)
  21. Dec(int64)
  22. Snapshot() Counter
  23. Clear()
  24. }
  25. func NewCounter() Counter {
  26. return &StandardCounter{
  27. count: 0,
  28. }
  29. }
  30. type StandardCounter struct {
  31. count int64
  32. }
  33. func (c *StandardCounter) Count() int64 {
  34. return atomic.LoadInt64(&c.count)
  35. }
  36. func (c *StandardCounter) Inc(count int64) {
  37. atomic.AddInt64(&c.count, count)
  38. }
  39. func (c *StandardCounter) Dec(count int64) {
  40. atomic.AddInt64(&c.count, -count)
  41. }
  42. func (c *StandardCounter) Snapshot() Counter {
  43. tmp := &StandardCounter{
  44. count: atomic.LoadInt64(&c.count),
  45. }
  46. return tmp
  47. }
  48. func (c *StandardCounter) Clear() {
  49. atomic.StoreInt64(&c.count, 0)
  50. }