Created
March 29, 2011 21:00
-
-
Save JakubOboza/893286 to your computer and use it in GitHub Desktop.
cache or not to cache
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
require "benchmark" | |
module Functional | |
def memo | |
cache = {} | |
lambda do |*args| | |
unless cache.has_key?(args) | |
cache[args] = self[*args] | |
end | |
cache[args] | |
end | |
end | |
def bench | |
[30, 35, 38].each do |n| | |
time = Benchmark.measure do | |
self[n] | |
end | |
puts "n = #{n} time = #{time}" | |
end | |
end | |
end | |
class Proc | |
include Functional | |
end | |
fib = lambda{|x| | |
if x < 2 | |
return 1 | |
else | |
fib[x - 1] + fib[x - 2] | |
end | |
} | |
fibm = lambda{|x| | |
if x < 2 | |
return 1 | |
else | |
fibm[x - 1] + fibm[x - 2] | |
end | |
}.memo | |
[fib, fibm].each do |foo| | |
foo.bench | |
end |
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
# not cached time | |
n = 30 time = 0.730000 0.000000 0.730000 ( 0.739614) | |
n = 35 time = 8.150000 0.040000 8.190000 ( 8.241662) | |
n = 38 time = 34.240000 0.140000 34.380000 ( 34.878019) | |
# cached time | |
n = 30 time = 0.000000 0.000000 0.000000 ( 0.000376) | |
n = 35 time = 0.000000 0.000000 0.000000 ( 0.000092) | |
n = 38 time = 0.000000 0.000000 0.000000 ( 0.000101) | |
# 34.87 sec vs 0.000101 :DDDD |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment