Skip to content

Instantly share code, notes, and snippets.

@danielpowell4
Created September 13, 2016 04:26
Show Gist options
  • Save danielpowell4/e046da134c309e82f049b797ed50647f to your computer and use it in GitHub Desktop.
Save danielpowell4/e046da134c309e82f049b797ed50647f to your computer and use it in GitHub Desktop.
Iterative and recursive fibonacci methods in Ruby with speed test
# -- 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