given a list of periods, already sorted, and containing no dups.
periods := periods{
period{min: 0, max: time.Millisecond},
period{min: time.Millisecond, max: time.Millisecond * 1},
period{min: time.Millisecond * 1, max: time.Millisecond * 2},
period{min: time.Millisecond * 2, max: time.Millisecond * 7},
period{min: time.Millisecond * 7, max: 0},
}
with the types periods and period defined as
type periods []period
func (ks periods) index(v time.Duration) period {
for i := 0; i < len(ks); i++ {
if ks[i].contains(v) {
return ks[i]
}
}
return period{}
}
type period struct {
min time.Duration
max time.Duration
}
func (k period) String() string {
if k.max == 0 && k.max < k.min {
return fmt.Sprintf("%v-", k.min)
}
return fmt.Sprintf("%v-%v", k.min, k.max)
}
func (k period) contains(t time.Duration) bool {
if t <= 0 && k.min == 0 {
return true
}
return t > k.min && (k.max == 0 || t <= k.max)
}
The full code is available at https://play.golang.org/p/cDmQ7Ho6hUI
Can you suggest solution(s) to improve the search implementation in the periods.index function ?
Also, can you provide a factorized solution such as it is possible to re use the implementation ? A generics included solution is OK for that i can still specialize using code gen.
A benchmark is included
func BenchmarkIndex(b *testing.B) {
periods := periods{
period{min: 0, max: 8000},
period{min: 8000, max: 16000},
period{min: 16000, max: 24000},
period{min: 24000, max: 32000},
period{min: 32000, max: 40000},
period{min: 40000, max: 48000},
period{min: 48000, max: 56000},
period{min: 56000, max: 64000},
period{min: 64000, max: 72000},
period{min: 72000, max: 80000},
period{min: 80000, max: 0},
}
inputs := []time.Duration{
time.Duration(0),
time.Duration(72000 + 1),
time.Duration(80000 + 1),
}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for _, input := range inputs {
_ = periods.index(input)
}
}
}