/ Published in: Ruby

Connect to three sites using threads and without using them. Fetch the response. Measure the benchmark.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
# encoding: utf-8 require 'net/http' require 'benchmark' class StatusFetcher attr_reader :result def initialize @result = [] end def self.start! new end end class ThreadStatusFetcher < StatusFetcher def initialize super threads = [] %w{ stackoverflow.com superuser.com systemfault.com }.each do |page| threads << Thread.new(page) do |url| http = Net::HTTP.new(url, 80) @result << "#{url}: #{http.get('/').message}" end end threads.each(&:join) end end class SimpleStatusFetcher < StatusFetcher def initialize super %w{ stackoverflow.com superuser.com systemfault.com }.each do |url| http = Net::HTTP.new(url, 80) @result << "#{url}: #{http.get('/').message}" end end end Benchmark.bm(8) do |r| r.report('simple') { SimpleStatusFetcher.start!.result } r.report('thread') { ThreadStatusFetcher.start!.result } end
Comments
