视频教程
『阿男的代码漫谈时间』*02*让我们聊一聊缓存
本节课代码
class="ruby">
require 'set'
class Generator
def self.unique_keys(n, max)
randoms = Set.new
loop do
randoms << rand(max)
return randoms.to_a if randoms.size >= n
end
end
def self.generate_sample_data
open('data_sample.txt', 'w') { |f|
unique_keys(100000, 100000).each do |key|
f.puts "#{key}:#{(0...5).map { ('a'...'z').to_a[rand(26)] }.join}"
end
}
end
end
class Searcher
def search(target_key)
File.open('data_sample.txt', 'r') do |f|
f.each_line do |line|
entry = line.split(':')
key = entry[0]
val = entry[1]
if key.to_i == target_key
puts "#{key}: #{val}"
return entry
end
end
end
end
end
searcher = Searcher.new
(0..500).each do
searcher.search(rand(10))
end
class Cache
def initialize
@repo = Hash.new
@query_times = 0
@missed_times = 0
end
def read(key)
@query_times += 1
if (@repo[key] == nil)
@missed_times += 1
return nil
else
return @repo[key]
end
end
def write(key, val)
@repo[key] = val
end
def hit_rate
return (@query_times - @missed_times).to_f / @query_times
end
end
class CachedSearcher
def initialize
@cache = Cache.new
end
attr_reader :cache
def search(target_key)
if @cache.read(target_key) != nil
puts "#{target_key}: #{@cache.read(target_key)}"
return
else
File.open('data_sample.txt', 'r') do |f|
f.each_line do |line|
entry = line.split(':')
key = entry[0].to_i
val = entry[1]
if key == target_key
@cache.write(key, val)
puts "#{key}: #{val}"
return entry
end
end
end
end
end
end
# cached_searcher = CachedSearcher.new
# (0..500).each do
# cached_searcher.search(rand(10))
# end
# puts "cache hit rate: #{cached_searcher.cache.hit_rate}"
- data_sample.txt.zip (673 KB)
- 下载次数: 0