Created
February 17, 2011 10:02
-
-
Save apeiros/831425 to your computer and use it in GitHub Desktop.
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
# An example implementation of caching | |
# WARNING: this implementation does not feature any pruning/expiration strategy, | |
# be careful not to create a memory leak | |
require 'thread' | |
module Cacheable | |
@global_cache = {} | |
@mutex = Mutex.new | |
class << self | |
attr_reader :global_cache | |
attr_reader :mutex | |
end | |
def cached(key) | |
value = cache_read(key) | |
unless value then | |
value = yield | |
cache_write(key, value) | |
end | |
value | |
end | |
def cache_write(key, value) | |
Cacheable.mutex.synchronize do | |
Cacheable.global_cache[key] = value | |
end | |
end | |
def cache_read(key) | |
Cacheable.mutex.synchronize do | |
Cacheable.global_cache[key] | |
end | |
end | |
end | |
class CacheDemo | |
include Cacheable | |
# a slow and uncached implementation of fibonacchi | |
def uncached_fib(n) | |
return n if n < 2 | |
uncached_fib(n-2)+uncached_fib(n-1) | |
end | |
# a slow but cached implementation of fibonacchi | |
def fib(n) | |
return n if n < 2 | |
cached("CacheDemo\#fib#{n}") do | |
fib(n-2)+fib(n-1) | |
end | |
end | |
end | |
calc_fib = CacheDemo.new | |
start = Time.now | |
puts "Result: #{calc_fib.uncached_fib(30)}" | |
stop = Time.now | |
printf "Uncached: %.1fms\n", (stop-start)*1000 | |
start = Time.now | |
puts "Result: #{calc_fib.fib(30)}" | |
stop = Time.now | |
printf "First time: %.1fms\n", (stop-start)*1000 | |
start = Time.now | |
puts "Result: #{calc_fib.fib(30)}" | |
stop = Time.now | |
printf "Second time: %.1fms\n", (stop-start)*1000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment