require 'benchmark'
require 'open-uri'

require 'rubygems'
require 'curb'
require 'threadify'

#
# new numbers showing speeds of http get requests between curl shell, curl
# api, and open-uri in a serial or parallel (threaded) fashion.  in the end
# threaded open-uri call is the simplest and almost as fast as the rest, but
# only the shell curl call could easily be parrallelized on windoze.
#

n = 42
threads = 8

Benchmark.benchmark do |bm|

#
# comparing shell curl cmd, curl api, and open-uri
#

  bm.report 'shelling out to curl' do
    n.times do
      `curl --silent --location http://google.com`
    end
  end

  bm.report 'curl via api' do
    curl = Curl::Easy.new 'http://google.com'
    curl.follow_location = true
    n.times do
      curl.perform
      curl.body_str
    end
  end

  bm.report 'open-uri' do
    n.times do
      open('http://google.com'){|socket| socket.read}
    end
  end

#
# same as above - but using threadify
#

  bm.report 'shelling out to curl - with threadify' do
    Array.new(n).threadify(threads) do
      `curl --silent --location http://google.com`
    end
  end

  bm.report 'curl via api - with threadify' do
    Array.new(n).threadify(threads) do
      curl = Curl::Easy.new 'http://google.com'
      curl.follow_location = true
      curl.perform
      curl.body_str
    end
  end

  bm.report 'open-uri - with threadify' do
    Array.new(n).threadify(threads) do
      open('http://google.com'){|socket| socket.read}
    end
  end

end

__END__

shelling out to curl
  0.000000   0.050000   0.410000 (18.749870)

curl via api
  0.030000   0.030000   0.060000 (18.773771)

open-uri
  0.210000   0.140000   0.350000 (21.240193)

shelling out to curl - with threadify
  0.010000   0.080000   0.420000 (3.240552)

curl via api - with threadify
  0.060000   0.050000   0.110000 (2.730689)

open-uri - with threadify
  0.260000   0.170000   0.430000 (3.464913)