Skip to content

Instantly share code, notes, and snippets.

@lucatironi
Created September 28, 2014 10:07
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 lucatironi/e7c07c212146aa41bf1b to your computer and use it in GitHub Desktop.
Save lucatironi/e7c07c212146aa41bf1b to your computer and use it in GitHub Desktop.
Fibonacci Comparison
# Naive slow implementation
def simple_fib(n)
return n if (0..1).include?(n)
simple_fib(n - 1) + simple_fib(n - 2)
end
# Recursive fast implementation
def rec_fib(n)
rec = -> (a, b, n) { n == 0 ? a : rec.call(b, a + b, n - 1) }
rec.call(0, 1, n)
end
# Benchmark
require 'benchmark'
n = 30
Benchmark.bm(11) do |x|
x.report("simple_fib:") { (0..n).map { |i| simple_fib(i) } }
x.report("rec_fib:") { (0..n).map { |i| rec_fib(i) } }
end
# user system total real
# simple_fib: 1.360000 0.000000 1.360000 ( 1.364467)
# rec_fib: 0.000000 0.000000 0.000000 ( 0.000156)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment