Skip to content

Instantly share code, notes, and snippets.

@TeWu
Created November 28, 2016 18:48
Show Gist options
  • Save TeWu/cc181b9efbb582d4b41c3b21d2c43c28 to your computer and use it in GitHub Desktop.
Save TeWu/cc181b9efbb582d4b41c3b21d2c43c28 to your computer and use it in GitHub Desktop.
require 'benchmark'
NA = 1000000
N = 1000
ARR = Array.new(NA) { rand }.freeze
Benchmark.bm do |x|
x.report("one iteration") do
N.times do
acc = 0
ARR.each do |e|
acc += e >= 0.3 ? e + 2 : 0
end
end
end
x.report("many iterations") do
N.times do
acc = ARR.select {|e| e >= 0.3 }
.map {|e| e + 2 }
.reduce(0, :+)
end
end
end
##
## user system total real
## one iteration 87.610000 0.000000 87.610000 ( 87.631403)
## many iterations 138.400000 0.030000 138.430000 (138.454974)
##
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment