Created
April 24, 2016 14:00
-
-
Save GeorgeTaveras1231/b716bf4289a825755f5e348f9cf8c35d to your computer and use it in GitHub Desktop.
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' | |
module Fib | |
module_function | |
def fib(n) | |
if n <= 1 | |
n | |
else | |
fib(n - 1) + fib(n - 2) | |
end | |
end | |
def memoized_fib(n) | |
@cache ||= {} | |
@cache[n] ||= if n <= 1 | |
n | |
else | |
memoized_fib(n - 1) + memoized_fib(n - 2) | |
end | |
end | |
end | |
puts "Un memoized fib" | |
puts Benchmark.measure { Fib.fib(40) } | |
# 13.160000 0.020000 13.180000 ( 13.189041) | |
puts "memoized fib" | |
puts Benchmark.measure { Fib.memoized_fib(40) } | |
# 0.000000 0.000000 0.000000 ( 0.000021) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment