Skip to content

Commit

Permalink
Use binary search for histogram buckets
Browse files Browse the repository at this point in the history
  • Loading branch information
simpl1g committed Nov 2, 2024
1 parent 5514b2b commit 3f052fd
Showing 1 changed file with 12 additions and 12 deletions.
24 changes: 12 additions & 12 deletions lib/prometheus/client/histogram.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# encoding: UTF-8
# frozen_string_literal: true

require 'prometheus/client/metric'

Expand Down Expand Up @@ -37,8 +37,8 @@ def self.linear_buckets(start:, width:, count:)
count.times.map { |idx| start.to_f + idx * width }
end

def self.exponential_buckets(start:, factor: 2, count:)
count.times.map { |idx| start.to_f * factor ** idx }
def self.exponential_buckets(start:, count:, factor: 2)
count.times.map { |idx| start.to_f * factor**idx }
end

def with_labels(labels)
Expand Down Expand Up @@ -67,16 +67,16 @@ def type
# https://prometheus.io/docs/practices/histograms/#count-and-sum-of-observations
# for details.
def observe(value, labels: {})
bucket = buckets.find {|upper_limit| upper_limit >= value }
bucket = "+Inf" if bucket.nil?
bucket = buckets.bsearch { |upper_limit| upper_limit >= value }
bucket = '+Inf' if bucket.nil?

base_label_set = label_set_for(labels)

# This is basically faster than doing `.merge`
bucket_label_set = base_label_set.dup
bucket_label_set[:le] = bucket.to_s
sum_label_set = base_label_set.dup
sum_label_set[:le] = "sum"
sum_label_set[:le] = 'sum'

@store.synchronize do
@store.increment(labels: bucket_label_set, by: 1)
Expand All @@ -88,7 +88,7 @@ def observe(value, labels: {})
def get(labels: {})
base_label_set = label_set_for(labels)

all_buckets = buckets + ["+Inf", "sum"]
all_buckets = buckets + ['+Inf', 'sum']

@store.synchronize do
all_buckets.each_with_object({}) do |upper_limit, acc|
Expand All @@ -104,8 +104,8 @@ def values
values = @store.all_values

result = values.each_with_object({}) do |(label_set, v), acc|
actual_label_set = label_set.reject{|l| l == :le }
acc[actual_label_set] ||= @buckets.map{|b| [b.to_s, 0.0]}.to_h
actual_label_set = label_set.reject { |l| l == :le }
acc[actual_label_set] ||= @buckets.map { |b| [b.to_s, 0.0] }.to_h
acc[actual_label_set][label_set[:le].to_s] = v
end

Expand All @@ -118,7 +118,7 @@ def init_label_set(labels)
base_label_set = label_set_for(labels)

@store.synchronize do
(buckets + ["+Inf", "sum"]).each do |bucket|
(buckets + ['+Inf', 'sum']).each do |bucket|
@store.set(labels: base_label_set.merge(le: bucket.to_s), val: 0)
end
end
Expand All @@ -135,8 +135,8 @@ def accumulate_buckets(h)
bucket_acc += bucket_value
end

inf_value = h["+Inf"] || 0.0
h["+Inf"] = inf_value + bucket_acc
inf_value = h['+Inf'] || 0.0
h['+Inf'] = inf_value + bucket_acc
end

def reserved_labels
Expand Down

0 comments on commit 3f052fd

Please sign in to comment.