Skip to content

Commit bc1f2b2

Browse files
committed
Merge pull request #79 from prometheus/beorn7/histogram
Use binary search to pick bucket.
2 parents 38dbb2e + 79efd06 commit bc1f2b2

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

prometheus/histogram.go

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import (
1717
"fmt"
1818
"hash/fnv"
1919
"math"
20+
"sort"
2021
"sync/atomic"
2122

2223
"github.com/golang/protobuf/proto"
@@ -231,11 +232,18 @@ func (h *histogram) Desc() *Desc {
231232
}
232233

233234
func (h *histogram) Observe(v float64) {
234-
for i, upperBound := range h.upperBounds {
235-
if v <= upperBound {
236-
atomic.AddUint64(&h.counts[i], 1)
237-
break
238-
}
235+
// TODO(beorn7): For small numbers of buckets (<30), a linear search is
236+
// slightly faster than the binary search. If we really care, we could
237+
// switch from one search strategy to the other depending on the number
238+
// of buckets.
239+
//
240+
// Microbenchmarks (BenchmarkHistogramNoLabels):
241+
// 11 buckets: 38.3 ns/op linear - binary 48.7 ns/op
242+
// 100 buckets: 78.1 ns/op linear - binary 54.9 ns/op
243+
// 300 buckets: 154 ns/op linear - binary 61.6 ns/op
244+
i := sort.SearchFloat64s(h.upperBounds, v)
245+
if i < len(h.counts) {
246+
atomic.AddUint64(&h.counts[i], 1)
239247
}
240248
atomic.AddUint64(&h.count, 1)
241249
for {

0 commit comments

Comments
 (0)