Skip to content

Instantly share code, notes, and snippets.

@jish
Created May 21, 2009 16:18
Show Gist options
  • Save jish/115551 to your computer and use it in GitHub Desktop.
Save jish/115551 to your computer and use it in GitHub Desktop.
require 'benchmark'
def loopy_fib(num)
return 1 if num == 1
return 1 if num == 2
x = 1
y = 1
a = 0
(num - 2).times do
a = x + y
x = y
y = a
end
a
end
def recursive_fib(n)
return 1 if n == 1 || n == 2
recursive_fib(n - 2) + recursive_fib(n - 1)
end
def benchmark(iterations)
benchmark = Benchmark.measure do
1.upto(iterations) do |i|
yield(i)
end
end
benchmark.real
end
1.upto(6) do |i|
num = i * 5
puts "computing fib(1) to fib(#{num})"
puts " loopy: %6.5f seconds" % benchmark(num) { |j| loopy_fib(j) }
puts " recursive: %6.5f seconds" % benchmark(num) { |j| recursive_fib(j) }
end
#
# Output from my MacBook Pro:
#
# computing fib(1) to fib(5)
# loopy: 0.00002 seconds
# recursive: 0.00004 seconds
# computing fib(1) to fib(10)
# loopy: 0.00003 seconds
# recursive: 0.00021 seconds
# computing fib(1) to fib(15)
# loopy: 0.00006 seconds
# recursive: 0.00226 seconds
# computing fib(1) to fib(20)
# loopy: 0.00019 seconds
# recursive: 0.02350 seconds
# computing fib(1) to fib(25)
# loopy: 0.00022 seconds
# recursive: 0.25846 seconds
# computing fib(1) to fib(30)
# loopy: 0.00042 seconds
# recursive: 2.83221 seconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment