github.com/linapex/ethereum-dpos-chinese@v0.0.0-20190316121959-b78b3a4a1ece/metrics/counter.go (about) 1 2 //<developer> 3 // <name>linapex 曹一峰</name> 4 // <email>linapex@163.com</email> 5 // <wx>superexc</wx> 6 // <qqgroup>128148617</qqgroup> 7 // <url>https://jsq.ink</url> 8 // <role>pku engineer</role> 9 // <date>2019-03-16 12:09:41</date> 10 //</624342647628107776> 11 12 package metrics 13 14 import "sync/atomic" 15 16 //计数器保存一个可以递增和递减的Int64值。 17 type Counter interface { 18 Clear() 19 Count() int64 20 Dec(int64) 21 Inc(int64) 22 Snapshot() Counter 23 } 24 25 //GetOrRegisterCounter返回现有计数器或构造和注册 26 //一个新的标准计数器。 27 func GetOrRegisterCounter(name string, r Registry) Counter { 28 if nil == r { 29 r = DefaultRegistry 30 } 31 return r.GetOrRegister(name, NewCounter).(Counter) 32 } 33 34 //NewCounter构造一个新的标准计数器。 35 func NewCounter() Counter { 36 if !Enabled { 37 return NilCounter{} 38 } 39 return &StandardCounter{0} 40 } 41 42 //NewRegisteredCounter构造并注册新的标准计数器。 43 func NewRegisteredCounter(name string, r Registry) Counter { 44 c := NewCounter() 45 if nil == r { 46 r = DefaultRegistry 47 } 48 r.Register(name, c) 49 return c 50 } 51 52 //CounterSnapshot是另一个计数器的只读副本。 53 type CounterSnapshot int64 54 55 //清晰的恐慌。 56 func (CounterSnapshot) Clear() { 57 panic("Clear called on a CounterSnapshot") 58 } 59 60 //count返回快照拍摄时的计数。 61 func (c CounterSnapshot) Count() int64 { return int64(c) } 62 63 //十足恐慌。 64 func (CounterSnapshot) Dec(int64) { 65 panic("Dec called on a CounterSnapshot") 66 } 67 68 //公司恐慌。 69 func (CounterSnapshot) Inc(int64) { 70 panic("Inc called on a CounterSnapshot") 71 } 72 73 //快照返回快照。 74 func (c CounterSnapshot) Snapshot() Counter { return c } 75 76 //nilcounter是一个禁止操作的计数器。 77 type NilCounter struct{} 78 79 //清除是不可操作的。 80 func (NilCounter) Clear() {} 81 82 //计数是不允许的。 83 func (NilCounter) Count() int64 { return 0 } 84 85 //DEC是NO-OP。 86 func (NilCounter) Dec(i int64) {} 87 88 //公司是一个NO-OP。 89 func (NilCounter) Inc(i int64) {} 90 91 //快照是不可操作的。 92 func (NilCounter) Snapshot() Counter { return NilCounter{} } 93 94 //StandardCounter是计数器的标准实现,它使用 95 //同步/atomic包以管理单个int64值。 96 type StandardCounter struct { 97 count int64 98 } 99 100 //清除将计数器设置为零。 101 func (c *StandardCounter) Clear() { 102 atomic.StoreInt64(&c.count, 0) 103 } 104 105 //count返回当前计数。 106 func (c *StandardCounter) Count() int64 { 107 return atomic.LoadInt64(&c.count) 108 } 109 110 //DEC按给定的数量递减计数器。 111 func (c *StandardCounter) Dec(i int64) { 112 atomic.AddInt64(&c.count, -i) 113 } 114 115 //inc将计数器递增给定的数量。 116 func (c *StandardCounter) Inc(i int64) { 117 atomic.AddInt64(&c.count, i) 118 } 119 120 //快照返回计数器的只读副本。 121 func (c *StandardCounter) Snapshot() Counter { 122 return CounterSnapshot(c.Count()) 123 } 124