Skip to content

Instantly share code, notes, and snippets.

@sandro
Created August 27, 2011 01:34
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sandro/1174840 to your computer and use it in GitHub Desktop.
Save sandro/1174840 to your computer and use it in GitHub Desktop.
Parallel HTTParty requests using threads
require 'rubygems'
require 'httparty'
require 'benchmark'
require 'thread'
class Google
include HTTParty
base_uri 'http://google.com'
def self.benchmark
puts "#{name} took #{Benchmark.realtime { get('/') }}"
end
end
class TheChangeLog
include HTTParty
base_uri 'http://thechangelog.com/'
def self.benchmark
puts "#{name} took #{Benchmark.realtime { get('/') }}"
end
end
def non_threaded
Google.benchmark
TheChangeLog.benchmark
end
def threaded
threads = []
threads << Thread.new { Google.benchmark }
threads << Thread.new { TheChangeLog.benchmark}
threads.each {|t| t.join}
end
def run(type)
puts "Running #{type.to_s.capitalize}"
total = Benchmark.realtime { send(type) }
puts "Total time: #{total}\n\n"
end
run(:non_threaded)
run(:threaded)
=begin
Sample Results:
Running Non_threaded
Google took 1.28137707710266
TheChangeLog took 1.66646480560303
Total time: 2.94795608520508
Running Threaded
TheChangeLog took 0.342212915420532
Google took 0.89379620552063
Total time: 0.893890142440796
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment