forked from influxdata/influxdb-comparisons
-
Notifications
You must be signed in to change notification settings - Fork 0
/
time_interval.go
65 lines (52 loc) · 1.57 KB
/
time_interval.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
package bulk_query_gen
import (
"math/rand"
"time"
)
// TimeInterval represents an interval of time.
type TimeInterval struct {
Start, End time.Time
}
// NewTimeInterval constructs a TimeInterval.
func NewTimeInterval(start, end time.Time) TimeInterval {
return TimeInterval{
Start: start,
End: end,
}
}
// Duration converts a TimeInterval to a time.Duration.
func (ti *TimeInterval) Duration() time.Duration {
return ti.End.Sub(ti.Start)
}
// RandWindow creates a TimeInterval of duration `window` at a uniformly-random
// start time within this time interval.
func (ti *TimeInterval) RandWindow(window time.Duration) TimeInterval {
lower := ti.Start.UnixNano()
upper := ti.End.Add(-window).UnixNano()
if upper <= lower {
panic("logic error: bad time bounds")
}
start := lower + rand.Int63n(upper-lower)
end := start + window.Nanoseconds()
x := NewTimeInterval(time.Unix(0, start), time.Unix(0, end))
if x.Duration() != window {
panic("logic error: generated interval does not equal window")
}
return x
}
// StartString formats the start of the time interval.
func (ti *TimeInterval) StartString() string {
return ti.Start.UTC().Format(time.RFC3339)
}
// EndString formats the end of the time interval.
func (ti *TimeInterval) EndString() string {
return ti.End.UTC().Format(time.RFC3339)
}
// StartUnixNano returns the start time as nanoseconds.
func (ti *TimeInterval) StartUnixNano() int64 {
return ti.Start.UTC().UnixNano()
}
// EndUnixNano returns the end time as nanoseconds.
func (ti *TimeInterval) EndUnixNano() int64 {
return ti.End.UTC().UnixNano()
}