class Zold::Stress::Stats

Stats

Public Class Methods

new(log: Zold::Log::NULL) click to toggle source
# File lib/zold/stress/stats.rb, line 36
def initialize(log: Zold::Log::NULL)
  @history = {}
  @mutex = Mutex.new
  @log = log
end

Public Instance Methods

avg(metric) click to toggle source
# File lib/zold/stress/stats.rb, line 50
def avg(metric)
  sum(metric).to_f / [total(metric), 1].max
end
exec(metric, swallow: true) { || ... } click to toggle source
# File lib/zold/stress/stats.rb, line 76
def exec(metric, swallow: true)
  start = Time.now
  yield
  put(metric + '_ok', Time.now - start)
rescue StandardError => ex
  put(metric + '_error', Time.now - start)
  @log.error(Backtrace.new(ex))
  puts '!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'
  raise ex unless swallow
ensure
  put(metric, Time.now - start)
end
exists?(metric) click to toggle source
# File lib/zold/stress/stats.rb, line 42
def exists?(metric)
  !@history[metric].nil?
end
put(metric, value) click to toggle source
# File lib/zold/stress/stats.rb, line 89
def put(metric, value)
  raise "Invalid type of \"#{value}\" (#{value.class.name})" unless value.is_a?(Integer) || value.is_a?(Float)
  @mutex.synchronize do
    @history[metric] = [] unless @history[metric]
    @history[metric] << { time: Time.now, value: value }
  end
end
sum(metric) click to toggle source
# File lib/zold/stress/stats.rb, line 54
def sum(metric)
  (@history[metric] || []).map { |a| a[:value] }.inject(&:+) || 0
end
to_json() click to toggle source
# File lib/zold/stress/stats.rb, line 58
def to_json
  @history.map do |m, h|
    data = h.map { |a| a[:value] }
    sum = data.inject(&:+) || 0
    [
      m,
      {
        'total': data.count,
        'sum': sum,
        'avg': (data.empty? ? 0 : (sum / data.count)),
        'max': data.max || 0,
        'min': data.min || 0,
        'age': (h.map { |a| a[:time] }.max || 0) - (h.map { |a| a[:time] }.min || 0)
      }
    ]
  end.to_h
end
total(metric) click to toggle source
# File lib/zold/stress/stats.rb, line 46
def total(metric)
  (@history[metric] || []).count
end