From 3f052fdaa2c545094faffe1d3357d4d81851ce5a Mon Sep 17 00:00:00 2001 From: Konstantin Ilchenko Date: Sat, 2 Nov 2024 23:47:17 +0100 Subject: [PATCH] Use binary search for histogram buckets --- lib/prometheus/client/histogram.rb | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/prometheus/client/histogram.rb b/lib/prometheus/client/histogram.rb index 6963f673..cd33e416 100644 --- a/lib/prometheus/client/histogram.rb +++ b/lib/prometheus/client/histogram.rb @@ -1,4 +1,4 @@ -# encoding: UTF-8 +# frozen_string_literal: true require 'prometheus/client/metric' @@ -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) @@ -67,8 +67,8 @@ 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) @@ -76,7 +76,7 @@ def observe(value, labels: {}) 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) @@ -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| @@ -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 @@ -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 @@ -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