-
Notifications
You must be signed in to change notification settings - Fork 0
/
stat.go
49 lines (39 loc) · 949 Bytes
/
stat.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package main
import (
"fmt"
"sync/atomic"
)
type CounterStat struct {
Total int64 `json:"total"`
Speed int64 `json:"speed"`
}
type AtomicSpeedCounter struct {
total int64
intervalSum int64
lastSpeed int64
}
func (p *AtomicSpeedCounter) Inc(i int) {
atomic.AddInt64(&p.total, int64(i))
atomic.AddInt64(&p.intervalSum, int64(i))
}
func (p *AtomicSpeedCounter) Rotate() {
old := atomic.SwapInt64(&p.intervalSum, 0)
p.lastSpeed = (old + StatRollFrequency - 1) / StatRollFrequency
}
func (p *AtomicSpeedCounter) Reset() {
p.total = 0
p.intervalSum = 0
p.lastSpeed = 0
}
func (p *AtomicSpeedCounter) Total() int64 {
return p.total
}
func (p *AtomicSpeedCounter) Speed() int64 {
return p.lastSpeed
}
func (p *AtomicSpeedCounter) String() string {
return fmt.Sprintf("total:%d,speed:%d", p.total, p.lastSpeed)
}
func (p *AtomicSpeedCounter) Json() *CounterStat {
return &CounterStat{Total: p.total, Speed: p.lastSpeed}
}