Skip to content

Instantly share code, notes, and snippets.

@ahoward
Created October 23, 2011 13:59
Show Gist options
  • Save ahoward/1307389 to your computer and use it in GitHub Desktop.
Save ahoward/1307389 to your computer and use it in GitHub Desktop.
#! /usr/bin/env ruby
##
# three strategies of modeling metrics:
#
# SimpleMetric: one metric per record
#
# HashMetric: an array of metrics per record
#
# EmbeddedMetric: an array of metric models per record
#
# the strategies of having sets per record would require some logic when one
# had to go back in time.
#
# the HashMetric is fastest and produces 1000s of times fewer records in the
# db. interesting...
##
#
require 'benchmark'
require 'rubygems'
require 'mongoid'
##
#
Mongoid.configure do |config|
config.master = Mongo::Connection.new.db("test")
end
##
#
N = Integer(ARGV.shift || 2 ** 13)
##
#
class SimpleMetric
include Mongoid::Document
field(:kind)
field(:value)
def self.emit!(attributes = {})j
create!(attributes)
end
def self.most_recent
all.limit(N)
end
end
class HashMetric
include Mongoid::Document
field(:metrics, :default => [])
Instance = create!
def self.emit!(attributes = {})
Instance.push_all(:metrics, [attributes])
end
def self.most_recent
last.metrics
end
end
class EmbeddedMetric
include Mongoid::Document
class Metric
include Mongoid::Document
field(:kind)
field(:value)
embedded_in(:embedded_metric, :class_name => 'EmbeddedMetric')
end
embeds_many(:metrics, :class_name => 'EmbeddedMetric::Metric')
Instance = create!
def self.emit!(attributes = {})
Instance.metrics.create!(attributes)
end
def self.most_recent
last.metrics
end
end
##
#
Benchmark.bm(3) do |bm|
[ SimpleMetric, HashMetric, EmbeddedMetric ].each do |strategy|
bm.report strategy.name do
N.times do
strategy.emit!(:kind => 'foo', :value => rand(10))
end
strategy.most_recent.each{}
end
end
end
__END__
ruby a.rb
user system total real
SimpleMetric 6.770000 0.290000 7.060000 ( 7.067250)
HashMetric 4.770000 0.130000 4.900000 ( 4.931874)
EmbeddedMetric 13.390000 0.200000 13.590000 ( 13.589994)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment