require 'date'
def memoize(fun)
memo = {}
-> (x) {
if memo.has_key?(x)
return memo[x]
end
r = method(fun).call(x)
memo[x] = r
return r
}
end
def fibonacci(x)
(x <= 2) ? 1 :
fibonacci(x - 1) + fibonacci(x - 2)
end
mem_fibonacci = memoize(:fibonacci)
for i in 1..2
start = DateTime.now
f37 = mem_fibonacci.call(37)
delta = DateTime.now - start
seconds = (delta * 24 * 60 * 60).to_f
puts "#{i}: f37 is #{f37}"
puts "#{i}: seconds is #{seconds}"
end
# prints:
# 1: f37 is 1.380856
# 1: seconds is 397,0302
# 2: f37 is 24157817
# 2: seconds is 0,000006
start = DateTime.now
f38 = mem_fibonacci.call(38)
delta = DateTime.now - start
seconds = (delta * 24 * 60 * 60).to_f
puts "f38 is #{f38}"
puts "seconds is #{seconds}"
# f38 is 39088169
# seconds is 2.326045
| This memoization method works well with non-recursive functions. Because it only remembers the result of the first function call. |