quantile: remove allocations
Blake Mizerany
9 years ago
4 | 4 |
)
|
5 | 5 |
|
6 | 6 |
func BenchmarkInsertTargeted(b *testing.B) {
|
|
7 |
b.ReportAllocs()
|
|
8 |
|
7 | 9 |
s := NewTargeted(0.01, 0.5, 0.9, 0.99)
|
8 | 10 |
b.ResetTimer()
|
9 | 11 |
for i := float64(0); i < float64(b.N); i++ {
|
168 | 168 |
type stream struct {
|
169 | 169 |
epsilon float64
|
170 | 170 |
n float64
|
171 | |
l []*Sample
|
|
171 |
l []Sample
|
172 | 172 |
ƒ invariant
|
173 | 173 |
}
|
174 | 174 |
|
|
197 | 197 |
c := s.l[i]
|
198 | 198 |
if c.Value > sample.Value {
|
199 | 199 |
// Insert at position i.
|
200 | |
s.l = append(s.l, nil)
|
|
200 |
s.l = append(s.l, Sample{})
|
201 | 201 |
copy(s.l[i+1:], s.l[i:])
|
202 | |
s.l[i] = &Sample{sample.Value, sample.Width, math.Floor(s.ƒ(s, r)) - 1}
|
|
202 |
s.l[i] = Sample{sample.Value, sample.Width, math.Floor(s.ƒ(s, r)) - 1}
|
203 | 203 |
i++
|
204 | 204 |
goto inserted
|
205 | 205 |
}
|
206 | 206 |
r += c.Width
|
207 | 207 |
}
|
208 | |
s.l = append(s.l, &Sample{sample.Value, sample.Width, 0})
|
|
208 |
s.l = append(s.l, Sample{sample.Value, sample.Width, 0})
|
209 | 209 |
i++
|
210 | 210 |
inserted:
|
211 | 211 |
s.n += sample.Width
|
|
236 | 236 |
return
|
237 | 237 |
}
|
238 | 238 |
x := s.l[len(s.l)-1]
|
|
239 |
xi := len(s.l) - 1
|
239 | 240 |
r := s.n - 1 - x.Width
|
240 | 241 |
|
241 | 242 |
for i := len(s.l) - 2; i >= 0; i-- {
|
242 | 243 |
c := s.l[i]
|
243 | 244 |
if c.Width+x.Width+x.Delta <= s.ƒ(s, r) {
|
244 | 245 |
x.Width += c.Width
|
|
246 |
s.l[xi] = x
|
245 | 247 |
// Remove element at i.
|
246 | 248 |
copy(s.l[i:], s.l[i+1:])
|
247 | |
s.l[len(s.l)-1] = nil
|
248 | 249 |
s.l = s.l[:len(s.l)-1]
|
|
250 |
xi -= 1
|
249 | 251 |
} else {
|
250 | 252 |
x = c
|
|
253 |
xi = i
|
251 | 254 |
}
|
252 | 255 |
r -= c.Width
|
253 | 256 |
}
|
|
255 | 258 |
|
256 | 259 |
func (s *stream) samples() Samples {
|
257 | 260 |
samples := make(Samples, len(s.l))
|
258 | |
for i, c := range s.l {
|
259 | |
samples[i] = *c
|
260 | |
}
|
|
261 |
copy(samples, s.l)
|
261 | 262 |
return samples
|
262 | 263 |
}
|