-
Notifications
You must be signed in to change notification settings - Fork 0
/
target.go
48 lines (39 loc) · 878 Bytes
/
target.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
package powernap
import "time"
type target struct {
target time.Time
d time.Duration
elapsed time.Duration
}
func newTarget(d time.Duration) target {
// If the duration is less than the cost of 2 time.Now() calls,
// There's no reason to do any calculations.
if d < (2 * timeNowCost) {
return target{
d: d,
}
}
return target{
target: time.Now().Add(d - timeNowCost),
d: d,
}
}
func (t target) sleep() {
// Return immediately if duration is less than it takes to get 2 timestamps
if t.target.UnixNano() == 0 {
return
}
if t.d-t.elapsed > safeDuration {
time.Sleep(t.d - t.elapsed - safeDuration)
}
for time.Now().Before(t.target) {
}
}
func (t target) sleepTight() {
// Return immediately if duration is less than it takes to get 2 timestamps
if t.target.UnixNano() == 0 {
return
}
for time.Now().Before(t.target) {
}
}