Skip to content

Instantly share code, notes, and snippets.

@vpereira
Created December 10, 2014 09:52
Show Gist options
  • Save vpereira/eb65610b48b3781575c6 to your computer and use it in GitHub Desktop.
Save vpereira/eb65610b48b3781575c6 to your computer and use it in GitHub Desktop.
require 'benchmark'
def div_by_2(n)
n % 2 == 0 ? true : false
end
a = 0.upto(rand(31337))
b = 0.upto(rand(31337))
def method_a(a,b)
a.each do |aa|
b.each do |bb|
return if div_by_2(aa ** bb - 1)
end
end
end
def method_b(a,b)
a.each do |aa|
b.any? do |bb|
div_by_2(aa ** bb - 1)
end
end
end
Benchmark.bm do |x|
x.report { method_b(a,b) }
x.report { method_a(a,b) }
end
# vpereira@linux-8njk:~> ruby t.rb
# user system total real
# 0.020000 0.000000 0.020000 ( 0.019316)
# 0.000000 0.000000 0.000000 ( 0.000010)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment