Sha256: 0e27ebc688561875a06a1b0c41b2b7d694acbbd0909e0bc18740ee3a75d56a9d

Contents?: true

Size: 1.62 KB

Versions: 4

Compression:

Stored size: 1.62 KB

Contents

# Copyright (c) 2018 Sqreen. All Rights Reserved.
# Please refer to our terms for more information: https://www.sqreen.io/terms.html

require 'sqreen/metrics/base'

module Sqreen
  module Metric
    # Takes numbers as samples and bins them (effectively, rounds them).
    # Also collect max values
    class Binning < Base
      BASE_KEY = 'base'.freeze
      FACTOR_KEY = 'factor'.freeze
      # upper bound of i-th bin is factor * base^(i-1)
      def initialize(opts={})
        options = opts.dup
        @base = options.delete(BASE_KEY)
        @factor = options.delete(FACTOR_KEY)
        super(options)
        log_base = Math.log(@base)
        log_factor = Math.log(@factor)
        @inv_log_base = 1 / log_base
        @add_parcel = - log_factor / log_base
        new_sample(Time.now.utc)
      end

      def update(_at, _key, x)
        h = @sample[OBSERVATION_KEY]
        bin = bin_no(x)
        h[bin] += 1
        h['max'] = x if x > h['max']
      end

      def next_sample(time)
        return nil if @sample[OBSERVATION_KEY].empty?
        super(time)
      end

      protected

      # these two are called by next_sample

      def finalize_sample(time)
        @sample[FINISH_KEY] = time
        h = @sample[OBSERVATION_KEY]
        @sample[OBSERVATION_KEY] = { 'u' => @factor, 'b' => @base, 'v' => h }
      end

      def new_sample(time)
        @sample = {
          OBSERVATION_KEY => Hash.new { |hash, key| hash[key] = 0 },
          START_KEY => time,
        }
      end

      private

      def bin_no(x)
        res = 2 + (@inv_log_base * Math.log(x) + @add_parcel).floor
        res < 1 ? 1 : res
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
sqreen-1.14.2-java lib/sqreen/metrics/binning.rb
sqreen-1.14.2 lib/sqreen/metrics/binning.rb
sqreen-1.14.1-java lib/sqreen/metrics/binning.rb
sqreen-1.14.1 lib/sqreen/metrics/binning.rb