forked from globalsign/mgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coarse_time.go
62 lines (54 loc) · 1.43 KB
/
coarse_time.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
package mgo
import (
"sync"
"sync/atomic"
"time"
)
// coarseTimeProvider provides a periodically updated (approximate) time value to
// amortise the cost of frequent calls to time.Now.
//
// A read throughput increase of ~6% was measured when using coarseTimeProvider with the
// high-precision event timer (HPET) on FreeBSD 11.1 and Go 1.10.1 after merging
// #116.
//
// Calling Now returns a time.Time that is updated at the configured interval,
// however due to scheduling the value may be marginally older than expected.
//
// coarseTimeProvider is safe for concurrent use.
type coarseTimeProvider struct {
once sync.Once
stop chan struct{}
last atomic.Value
}
// Now returns the most recently acquired time.Time value.
func (t *coarseTimeProvider) Now() time.Time {
return t.last.Load().(time.Time)
}
// Close stops the periodic update of t.
//
// Any subsequent calls to Now will return the same value forever.
func (t *coarseTimeProvider) Close() {
t.once.Do(func() {
close(t.stop)
})
}
// newcoarseTimeProvider returns a coarseTimeProvider configured to update at granularity.
func newcoarseTimeProvider(granularity time.Duration) *coarseTimeProvider {
t := &coarseTimeProvider{
stop: make(chan struct{}),
}
t.last.Store(time.Now())
go func() {
ticker := time.NewTicker(granularity)
for {
select {
case <-t.stop:
ticker.Stop()
return
case <-ticker.C:
t.last.Store(time.Now())
}
}
}()
return t
}