Return to Snippet

Revision: 48676
at July 7, 2011 16:26 by Shamaoke


Initial Code
# 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

Initial URL


Initial Description
Connect to three sites using threads and without using them. Fetch the response. Measure the benchmark.

Initial Title
Ruby. Thread benchmark

Initial Tags
ruby

Initial Language
Ruby