Created
October 23, 2012 01:01
-
-
Save runtasticwebdev/3936015 to your computer and use it in GitHub Desktop.
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 "rubygems" | |
require "benchmark" | |
def setup_array | |
array = [] | |
10_000_000.times { array << rand } | |
array | |
end | |
def modulo(step_size) | |
array = setup_array | |
result = [] | |
Benchmark.measure do | |
array.each_with_index do |element, index| | |
result << element if index % step_size == 1 | |
end | |
end | |
end | |
def step(step_size) | |
array = setup_array | |
result = [] | |
Benchmark.measure do | |
(0..array.length - 1).step(step_size).each do |index| | |
result << array[index] | |
end | |
end | |
end | |
puts "modulo, step_size = 2: #{modulo(2)}" | |
puts "step, step_size = 2: #{step(2)}" | |
puts "modulo, step_size = 1_000_000: #{modulo(1_000_000)}" | |
puts "step, step_size = 1_000_000: #{step(1_000_000)}" | |
# modulo, step_size = 2: 7.940000 0.100000 8.040000 ( 8.043250) | |
# step, step_size = 2: 2.050000 0.030000 2.080000 ( 2.075453) | |
# modulo, step_size = 1_000_000: 7.040000 0.090000 7.130000 ( 7.118047) | |
# step, step_size = 1_000_000: 0.000000 0.000000 0.000000 ( 0.000024) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment