-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.go
52 lines (43 loc) · 1.33 KB
/
helpers.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
package powernap
import (
"time"
)
// timeNowCost is an estimate of the cost of calling time.Now.
// This is usually in ~100-200ns. But can of course vary.
var timeNowCost = 100 * time.Nanosecond
// safeDuration is used for deciding when to use native time.Sleep().
// It should be pretty high as overshooting can fluctuate wildly.
var safeDuration = 500 * time.Microsecond
// NOTE: It seems that actually getting the time from the OS should be pretty fast (ASM).
// So the cost of calling time.Now(), should be in the last part - after actually getting the time.
func init() {
// Pre-calc timeNowCost
runs := 10000
start := time.Now()
for i := 0; i < runs; i++ {
time.Now()
}
timeNowCost = time.Now().Sub(start) / time.Duration(runs+1)
// Sleep a little
time.Sleep(100 * time.Millisecond)
// Run pre-calc of timeNowCost again
start = time.Now()
for i := 0; i < runs; i++ {
tmp := time.Now()
_ = tmp
}
timeNowCost = (timeNowCost + (time.Now().Sub(start) / time.Duration(runs+1))) / 2
// Pre-calc safeDuration
worst := time.Nanosecond
for i := 0; i < 1000; i++ {
start := time.Now()
time.Sleep(time.Nanosecond)
duration := time.Since(start)
if duration > worst {
worst = duration
}
}
// The iterations gives a rough idea of a worst case,
// but we want to be far away from the danger zone.
safeDuration = worst * 50
}