# coding: utf-8 require "base64" require 'rubygems' require 'redis' require 'digest/md5' require 'open-uri' options = { :timeout => 120, :thread_safe => true } host = ENV["REDIS_HOST"] || 'localhost' port = ENV["REDIS_PORT"] || 6379 db = ENV["REDIS_DB"] || 1 options.merge!({ :host => host, :port => port, :db => db }) redis = Redis.connect(options) @iterations = [1] 10.times { |i| @iterations << (i+1)*10 } 100.times { |i| @iterations << (i+1)*100 } @iterations.uniq! class WebPage attr_reader :redis, :ttl def initialize(redis, ttl = 900) @redis = redis @ttl = ttl end def read(url) unless d = get(url) d = open(url).read set(url, d) end d end private def set(url, page) k = key(url) @redis.set(k, page) @redis.expire(k, @ttl) end def get(url) @redis.get(key(url)) end def key(url) "webpage:#{Digest::MD5.hexdigest(url)}" end end class ResultStorer def self.save(time, iterations, filename) File.open(filename, 'a') {|f| f.write("#{time} - #{iterations}\n") } end end class Benchmark def self.run(filename, name) time_before = Time.now iterations = yield time_after = Time.now time_taken = time_after-time_before ResultStorer.save(time_taken, iterations, filename) print "#{name}: time: #{time_taken}\n" end end wp = WebPage.new(redis) 10.times do |attemp| @iterations.each do |i| time = Time.now.to_i Benchmark.run("not-cached-#{attemp}.txt", "Not cached: #{i}") do i.times { |j| open("http://127.0.0.1/phpmyadmin/?req=#{i}&time=#{time}") } i end Benchmark.run("cached-#{attemp}.txt", "Cached: #{i}") do i.times { |j| wp.read("http://127.0.0.1/phpmyadmin/?req=#{i}&time=#{time}") } i end end end