Skip to content

Instantly share code, notes, and snippets.

@rf-
Created September 4, 2011 03:53
Show Gist options
  • Save rf-/1192222 to your computer and use it in GitHub Desktop.
Save rf-/1192222 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'benchmark'
require 'ostruct'
unlocked = 100000.times.map { o = OpenStruct.new; o.timestamp = Time.now - Kernel.rand(10000000); o } ; nil
method1 = lambda {
achievements_per_day = Hash.new(0)
unlocked.each do |achievement|
achievements_per_day[achievement.timestamp.strftime("%D")] += 1 if achievement.timestamp
end
}
method2 = lambda {
achievements_per_day = unlocked.map(&:timestamp).compact.reduce(Hash.new(0)) { |accum, tstamp| accum[tstamp.strftime("%D")] += 1; accum }
}
avg_time = lambda { |n, fn|
n.times.map { Benchmark.realtime(&fn) }.reduce(:+) / n.to_f
}
puts avg_time[15, method1] # 0.9437
puts avg_time[15, method2] # 0.9125
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment