Last active
December 18, 2015 14:38
-
-
Save mjhea0/5798178 to your computer and use it in GitHub Desktop.
benchmark fibonacci sequence recursive vs iterative
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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