-
Notifications
You must be signed in to change notification settings - Fork 1
/
stopwatch.go
74 lines (64 loc) · 1.56 KB
/
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package confirmer
import (
"github.com/unioproject/tanglebeat/lib/utils"
"sync"
"time"
)
// stopwatchEntry with a given name must be started once
// first stop (earliest) will have effect of caling callback
// subsequent stops won't have any effect
type stopwatchEntry struct {
started uint64
stopped uint64
}
var stopwatches = make(map[string]stopwatchEntry)
var mutexStopwatch = &sync.Mutex{}
// creates or reinitializes stopwatch entry.
// Returns false if already exist
func StartStopwatch(name string) bool {
mutexStopwatch.Lock()
defer mutexStopwatch.Unlock()
_, exists := stopwatches[name]
stopwatches[name] = stopwatchEntry{started: utils.UnixMs(time.Now())}
return !exists
}
func StopStopwatch(name string) bool {
mutexStopwatch.Lock()
defer mutexStopwatch.Unlock()
entry, ok := stopwatches[name]
if !ok {
return false
}
if entry.stopped == 0 {
entry.stopped = utils.UnixMs(time.Now())
}
return true
}
func _get(name string) (uint64, uint64, bool) {
entry, ok := stopwatches[name]
if !ok {
return 0, 0, false
}
started := entry.started
var stopped uint64
if entry.stopped == 0 {
stopped = utils.UnixMs(time.Now())
} else {
stopped = entry.stopped
}
return started, stopped, true
}
func GetStopwatch(name string) (uint64, uint64, bool) {
mutexStopwatch.Lock()
defer mutexStopwatch.Unlock()
return _get(name)
}
func GetAndRemoveStopwatch(name string) (uint64, uint64, bool) {
mutexStopwatch.Lock()
defer mutexStopwatch.Unlock()
started, stopped, succ := _get(name)
if succ {
delete(stopwatches, name)
}
return started, stopped, succ
}