Skip to content

Instantly share code, notes, and snippets.

@GeorgeTaveras1231
Created April 24, 2016 14:00
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 GeorgeTaveras1231/b716bf4289a825755f5e348f9cf8c35d to your computer and use it in GitHub Desktop.
Save GeorgeTaveras1231/b716bf4289a825755f5e348f9cf8c35d to your computer and use it in GitHub Desktop.
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