Skip to content

Instantly share code, notes, and snippets.

@digitalplaywright
Created March 21, 2012 22:33
Show Gist options
  • Save digitalplaywright/9f853b237d0207996d92 to your computer and use it in GitHub Desktop.
Save digitalplaywright/9f853b237d0207996d92 to your computer and use it in GitHub Desktop.
benchmark
#!/usr/bin/env ruby
require 'benchmark'
AMOUNT_CALC_ATTRIBUTES = [:quantity, :price_per, :subtotal, :service_fee, :total, :trans_fee]
class AmountCalculated
attr_accessor *AMOUNT_CALC_ATTRIBUTES
attr_accessor :currency
def initialize(opts)
opts.each{|k,v| self.send("#{k}=", v)}
end
def <<(_other_class)
raise "different currencies can not be summed" unless _other_class.currency == self.currency
AMOUNT_CALC_ATTRIBUTES.each{|k| self.send("#{k}=", self.send("#{k}") + _other_class.send("#{k}" ) ) }
end
def +(_other_class)
raise "different currencies can not be summed" unless _other_class.currency == self.currency
new_values = {'currency' => self.currency}
AMOUNT_CALC_ATTRIBUTES.each{|k| new_values["#{k}"] = self.send("#{k}") + _other_class.send("#{k}" ) }
AmountCalculated.new(new_values)
end
end
am = AmountCalculated.new({ :quantity => rand(10), :price_per => rand(10), :subtotal => rand(10), :service_fee => rand(10), :trans_fee => rand(10), :total => rand(10), :currency => 'USD' })
Benchmark.bm do|b|
b.report('+') do
1_000_00.times do
am2 = AmountCalculated.new({ :quantity => rand(10), :price_per => rand(10), :subtotal => rand(10), :service_fee => rand(10), :trans_fee => rand(10), :total => rand(10), :currency => 'USD' })
am = am + am2
end
end
b.report('<<') do
1_000_00.times do
am2 = AmountCalculated.new({ :quantity => rand(10), :price_per => rand(10), :subtotal => rand(10), :service_fee => rand(10), :trans_fee => rand(10), :total => rand(10), :currency => 'USD' })
am << am2
end
end
end
@digitalplaywright
Copy link
Author

   user     system      total        real
  • 2.650000 0.000000 2.650000 ( 2.649692)

<< 1.860000 0.000000 1.860000 ( 1.864603)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment