forked from consensus-shipyard/mir
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stopwatch.go
59 lines (47 loc) · 911 Bytes
/
stopwatch.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
package mir
import (
"sync"
"time"
)
type Stopwatch struct {
sync.Mutex
t time.Duration
started time.Time
running bool
}
func (s *Stopwatch) Start() {
s.Lock()
defer s.Unlock()
if s.running {
panic("stopwatch already running")
}
s.running = true
s.started = time.Now()
}
func (s *Stopwatch) Stop() {
s.Lock()
defer s.Unlock()
if s.running {
s.t += time.Since(s.started)
s.running = false
}
}
func (s *Stopwatch) Reset() time.Duration {
s.Lock()
defer s.Unlock()
// This code is identical to the one in s.Stop().
// We cannot simply call stop here, because we are already holding the lock.
// Calling stop before acquiring the lock would, on the other hand, make Reset not atomic.
if s.running {
s.t += time.Since(s.started)
s.running = false
}
t := s.t
s.t = 0
return t
}
func (s *Stopwatch) Read() time.Duration {
s.Lock()
defer s.Unlock()
return s.t
}