forked from vova616/GarageEngine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Timer.go
47 lines (37 loc) · 892 Bytes
/
Timer.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
package engine
import (
"time"
)
type Timer map[interface{}]time.Time
const defaultKey = "0-=|DefTimer|=-0"
func NewTimer() Timer {
return make(map[interface{}]time.Time)
}
func (timer Timer) Start() {
timer.StartCustom(defaultKey)
}
func (timer Timer) Stop() time.Duration {
return timer.StopCustom(defaultKey)
}
func (timer Timer) Defer(result *time.Duration) func() {
return timer.DeferCustom(defaultKey, result)
}
func (timer Timer) DeferCustom(key interface{}, result *time.Duration) func() {
if result == nil {
panic("Result is nil.")
}
timer.StartCustom(key)
return func() {
*result = timer.StopCustom(key)
}
}
func (timer Timer) StartCustom(key interface{}) {
timer[key] = time.Now()
}
func (timer Timer) StopCustom(key interface{}) time.Duration {
startTime, exist := timer[key]
if !exist {
panic("No such custom key")
}
return time.Since(startTime)
}