github.com/yinchengtsinghua/golang-Eos-dpos-Ethereum@v0.0.0-20190121132951-92cc4225ed8e/metrics/counter.go (about) 1 2 //此源码被清华学神尹成大魔王专业翻译分析并修改 3 //尹成QQ77025077 4 //尹成微信18510341407 5 //尹成所在QQ群721929980 6 //尹成邮箱 yinc13@mails.tsinghua.edu.cn 7 //尹成毕业于清华大学,微软区块链领域全球最有价值专家 8 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 9 package metrics 10 11 import "sync/atomic" 12 13 //计数器保存一个可以递增和递减的Int64值。 14 type Counter interface { 15 Clear() 16 Count() int64 17 Dec(int64) 18 Inc(int64) 19 Snapshot() Counter 20 } 21 22 //GetOrRegisterCounter返回现有计数器或构造和注册 23 //一个新的标准计数器。 24 func GetOrRegisterCounter(name string, r Registry) Counter { 25 if nil == r { 26 r = DefaultRegistry 27 } 28 return r.GetOrRegister(name, NewCounter).(Counter) 29 } 30 31 //NewCounter构造一个新的标准计数器。 32 func NewCounter() Counter { 33 if !Enabled { 34 return NilCounter{} 35 } 36 return &StandardCounter{0} 37 } 38 39 //NewRegisteredCounter构造并注册新的标准计数器。 40 func NewRegisteredCounter(name string, r Registry) Counter { 41 c := NewCounter() 42 if nil == r { 43 r = DefaultRegistry 44 } 45 r.Register(name, c) 46 return c 47 } 48 49 //CounterSnapshot是另一个计数器的只读副本。 50 type CounterSnapshot int64 51 52 //清晰的恐慌。 53 func (CounterSnapshot) Clear() { 54 panic("Clear called on a CounterSnapshot") 55 } 56 57 //count返回快照拍摄时的计数。 58 func (c CounterSnapshot) Count() int64 { return int64(c) } 59 60 //十足恐慌。 61 func (CounterSnapshot) Dec(int64) { 62 panic("Dec called on a CounterSnapshot") 63 } 64 65 //公司恐慌。 66 func (CounterSnapshot) Inc(int64) { 67 panic("Inc called on a CounterSnapshot") 68 } 69 70 //快照返回快照。 71 func (c CounterSnapshot) Snapshot() Counter { return c } 72 73 //nilcounter是一个禁止操作的计数器。 74 type NilCounter struct{} 75 76 //清除是不可操作的。 77 func (NilCounter) Clear() {} 78 79 //计数是不允许的。 80 func (NilCounter) Count() int64 { return 0 } 81 82 //DEC是NO-OP。 83 func (NilCounter) Dec(i int64) {} 84 85 //公司是一个NO-OP。 86 func (NilCounter) Inc(i int64) {} 87 88 //快照是不可操作的。 89 func (NilCounter) Snapshot() Counter { return NilCounter{} } 90 91 //StandardCounter是计数器的标准实现,它使用 92 //同步/atomic包以管理单个int64值。 93 type StandardCounter struct { 94 count int64 95 } 96 97 //清除将计数器设置为零。 98 func (c *StandardCounter) Clear() { 99 atomic.StoreInt64(&c.count, 0) 100 } 101 102 //count返回当前计数。 103 func (c *StandardCounter) Count() int64 { 104 return atomic.LoadInt64(&c.count) 105 } 106 107 //DEC按给定的数量递减计数器。 108 func (c *StandardCounter) Dec(i int64) { 109 atomic.AddInt64(&c.count, -i) 110 } 111 112 //inc将计数器递增给定的数量。 113 func (c *StandardCounter) Inc(i int64) { 114 atomic.AddInt64(&c.count, i) 115 } 116 117 //快照返回计数器的只读副本。 118 func (c *StandardCounter) Snapshot() Counter { 119 return CounterSnapshot(c.Count()) 120 }