public
Created

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.