Skip to content

Instantly share code, notes, and snippets.

@mjhea0
Last active December 18, 2015 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjhea0/5798178 to your computer and use it in GitHub Desktop.
Save mjhea0/5798178 to your computer and use it in GitHub Desktop.
benchmark fibonacci sequence recursive vs iterative
require 'benchmark'
print "Recursive:\n"
def fibonacci(num)
num < 2 ? num : fibonacci(num-1) + fibonacci(num-2)
end
puts Benchmark.measure { 200.times { fibonacci(20) } }
print "\nIterative:\n"
def fib(num)
curr = 0
succ = 1
num.times { |n| curr, succ = succ, curr + succ }
curr
end
puts Benchmark.measure { 200.times { fib(20) } }
#--------------------Output--------------------#
# Recursive:
# 0.810000 0.000000 0.810000 ( 1.524704)
# Iterative:
# 0.000000 0.000000 0.000000 ( 0.001934)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment