Created
May 10, 2012 20:39
-
-
Save vessi/2655741 to your computer and use it in GitHub Desktop.
benchmark for found array "or" sum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
GC.disable | |
@array = [] | |
@array_size = 3000000 | |
@iterations = 100 | |
def prepopulate_array(mode) | |
@array = Array.new(@array_size, false) | |
if mode == 'first' | |
@array[0] = true | |
elsif mode == 'last' | |
@array[-1] = true | |
elsif mode == 'random' | |
@array[rand @array_size] = true | |
elsif mode == 'group' | |
(rand @array_size).times do | |
@array[rand @array_size] = true | |
end | |
end | |
end | |
['first', 'last', 'random', 'group'].each do |mode| | |
puts "#{mode} element" | |
Benchmark.bm(15) do |x| | |
x.report('prepopulation') do | |
prepopulate_array(mode) | |
end | |
x.report("uniq.inject") do | |
@iterations.times { @array.uniq.inject{|result, element| result or element} or false } | |
end | |
x.report("include?") do | |
@iterations.times { @array.include?(true) } | |
end | |
x.report("any?") do | |
@iterations.times { @array.any? } | |
end | |
x.report("find") do | |
@iterations.times { [email protected]{ |el| el } } | |
end | |
x.report("count") do | |
@iterations.times { @array.count(true) > 0 } | |
end | |
end | |
end |
Author
vessi
commented
May 10, 2012
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment