Skip to content

Instantly share code, notes, and snippets.

@mortenjohs
Last active December 10, 2015 14:08
Show Gist options
  • Save mortenjohs/4445874 to your computer and use it in GitHub Desktop.
Save mortenjohs/4445874 to your computer and use it in GitHub Desktop.
Benchmarking some simple counting functions in Ruby. ( http://m635j520.blogspot.fr/2013/01/counting-in-ruby-revisited-benchmarked.html )
require 'benchmark'
require 'benchmark/ips'
array = []
1000.times { array << rand(1000) }
N = 10000
module Enumerable
def count_by_function function
map = Hash.new(0)
self.each { |e| map[e.send(function)] += 1 }
map
end
def count_by_block (&block)
Hash[ self.group_by { |e| yield e }.map { |key, list| [key, list.length] } ]
end
end
Benchmark.bm do |r|
r.report("count_by_function ") do
N.times { array.count_by_function (:even?) }
end
r.report("count_by_block ") do
N.times { array.count_by_block { |e| e.even? } }
end
end
Benchmark.ips do |r|
r.report("count_by_function ") do
array.count_by_function (:even?)
end
r.report("count_by_block ") do
array.count_by_block { |e| e.even? }
end
end
# user system total real
# count_by_function 2.950000 0.000000 2.950000 ( 2.956958)
# count_by_block 2.350000 0.000000 2.350000 ( 2.352997)
#
# Calculating -------------------------------------
# count_by_function 326 i/100ms
# count_by_block 418 i/100ms
# -------------------------------------------------
# count_by_function 3243.3 (±2.8%) i/s - 16300 in 5.029924s
# count_by_block 4256.7 (±1.5%) i/s - 21318 in 5.009192s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment