Created
September 28, 2014 10:07
-
-
Save lucatironi/e7c07c212146aa41bf1b to your computer and use it in GitHub Desktop.
Fibonacci Comparison
This file contains hidden or 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
# 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