Created
September 13, 2016 04:26
-
-
Save danielpowell4/e046da134c309e82f049b797ed50647f to your computer and use it in GitHub Desktop.
Iterative and recursive fibonacci methods in Ruby with speed test
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
# -- Setup | |
# - recursive | |
def recursive_fib(x) | |
x < 2 ? x : recursive_fib(x-1) + recursive_fib(x-2) | |
end | |
# - iterative | |
def iterative_fib(num) | |
a = 0 | |
b = 1 | |
num.times do | |
temp = a | |
a = b | |
b = temp + b | |
end | |
return a | |
end | |
# -- Speed tests | |
require 'benchmark' | |
num = 35 | |
Benchmark.bm do |x| | |
x.report("recursive_fib") { recursive_fib(num) } | |
x.report("iterative_fib") { iterative_fib(num) } | |
end | |
# - output | |
# CL > ruby fibonacci.rb | |
# | |
# user system total real | |
# recursive_fib 1.200000 0.010000 1.210000 ( 1.214786) | |
# iterative_fib 0.000000 0.000000 0.000000 ( 0.000007) | |
# | |
# result => iterative wins | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment