Skip to content

Instantly share code, notes, and snippets.

@tjwallace
Created January 13, 2012 01:01
Show Gist options
  • Save tjwallace/1604082 to your computer and use it in GitHub Desktop.
Save tjwallace/1604082 to your computer and use it in GitHub Desktop.
require 'benchmark'
require 'net/http'
require 'uri'
def network_read(uri)
Net::HTTP.get_response uri
end
n = 100
uri = URI('http://google.com/')
Benchmark.bm(5) do |x|
x.report('loop ') { n.times { network_read(uri) } }
x.report('threads') {
n.times.map {
Thread.new { network_read(uri) }
}.map(&:join)
}
end
@cpb
Copy link

cpb commented Jan 13, 2012

  def network_read(uri)
    Net::HTTP.get_response uri
  end

task :benchmark do
  require 'benchmark'
  require 'net/http'
  require 'uri'
  require 'eventmachine'

  # [100,500,1000].each do |n|
    n = ENV['TIMES'].to_i
    target = n.times.inject(0) {|m,i| m+=i}

    puts "looking for #{n} requests... sum to #{target}"

    uri = URI('http://google.com/')

    Benchmark.bm(5) do |x|
      # x.report('loop   ') { n.times { network_read(uri) } }

      x.report('threads') {
          runs = 0
          n.times.map { |i|
            Thread.new { network_read(uri); runs += i }
          }.map(&:join)
          while(runs != target)

          end
      }

      x.report('eventmachine') {
        EM.run do
          conn = EM::Protocols::HttpClient2.connect 'google.com', 80
          runs = 0

          n.times do |p|
            req = conn.get("/")
            req.callback do |response|
              runs += p

              if runs == target
                EM.stop
              end
            end
          end

        end
      }
    end
  # end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment