-
Notifications
You must be signed in to change notification settings - Fork 0
/
stats.go
110 lines (86 loc) · 1.73 KB
/
stats.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"fmt"
"sync"
"time"
)
type stats struct {
lock *sync.RWMutex
nbBytes uint64
timeStart time.Time
timeStop time.Time
timePause time.Time
timePaused time.Duration
}
func newStats() *stats {
return &stats{
lock: &sync.RWMutex{},
}
}
func (s *stats) stop() {
s.lock.RLock()
if s.timeStart.IsZero() {
// Can't stop if not started
s.lock.RUnlock()
return
}
s.lock.RUnlock()
s.lock.Lock()
defer s.lock.Unlock()
if s.timeStop.IsZero() {
s.timeStop = time.Now()
}
}
func (s *stats) start() {
s.lock.Lock()
defer s.lock.Unlock()
if s.timeStart.IsZero() {
s.timeStart = time.Now()
} else if !s.timePause.IsZero() {
s.timePaused += time.Since(s.timePause)
s.timePause = time.Time{}
}
}
func (s *stats) pause() {
s.lock.RLock()
if s.timeStart.IsZero() || !s.timeStop.IsZero() {
s.lock.RUnlock()
return
}
s.lock.RUnlock()
s.lock.Lock()
defer s.lock.Unlock()
if s.timePause.IsZero() {
s.timePause = time.Now()
}
}
func (s *stats) addBytes(n uint64) {
s.lock.Lock()
defer s.lock.Unlock()
s.nbBytes += n
}
func (s *stats) bytes() uint64 {
s.lock.RLock()
defer s.lock.RUnlock()
return s.nbBytes
}
func (s *stats) bandwidth() float64 {
s.lock.RLock()
defer s.lock.RUnlock()
return (float64(s.nbBytes) / (1024 * 1024)) / s.duration().Seconds()
}
func (s *stats) duration() time.Duration {
s.lock.RLock()
defer s.lock.RUnlock()
if s.timeStart.IsZero() {
return 0
} else if s.timeStop.IsZero() {
return time.Since(s.timeStart) - s.timePaused
}
return s.timeStop.Sub(s.timeStart) - s.timePaused
}
func (s *stats) String() string {
s.lock.RLock()
defer s.lock.RUnlock()
return fmt.Sprintf("%v bytes | %-v | %0.4f MB/s", s.bytes(), s.duration(), s.bandwidth())
}