Skip to content

Instantly share code, notes, and snippets.

@Aupajo
Created June 9, 2014 04:04
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 Aupajo/5fc5bc86708fcd632c4a to your computer and use it in GitHub Desktop.
Save Aupajo/5fc5bc86708fcd632c4a to your computer and use it in GitHub Desktop.
require 'benchmark'
def fib_vanilla(n)
return n if (0..1).include?(n)
fib_vanilla(n - 1) + fib_vanilla(n - 2)
end
fib_memoized = Hash.new { |numbers, index|
numbers[index] = fib_memoized[index - 2] + fib_memoized[index - 1]
}.update(0 => 0, 1 => 1)
N = 40
Benchmark.bm do |x|
x.report { fib_memoized[N] }
x.report { fib_vanilla(N) }
end
# user system total real
# 0.000000 0.000000 0.000000 ( 0.000044)
# 70.300000 0.050000 70.350000 ( 70.471916)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment