Last active
April 11, 2023 06:26
-
-
Save soumyaray/6de752fe4ed43ba6b7c9 to your computer and use it in GitHub Desktop.
Async and Sync HTTP calls in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
def sync_call(urls) | |
urls.each do |u| | |
u['content'] = Net::HTTP.get( URI.parse(u['link']) ) | |
end | |
end | |
def async_call(urls) | |
threads = urls.map do |u| | |
Thread.new do | |
u['content'] = Net::HTTP.get( URI.parse(u['link']) ) | |
end | |
end | |
threads.each(&:join) | |
end | |
def timer(method) | |
urls = [ | |
{'link' => 'http://www.google.com/'}, | |
{'link' => 'http://www.facebook.com/'}, | |
{'link' => 'http://www.yahoo.com/'}, | |
{'link' => 'http://www.microsoft.com/'}, | |
{'link' => 'http://www.rubygems.org/'}, | |
{'link' => 'http://www.nthu.edu.tw/'}, | |
{'link' => 'https://github.com/'}, | |
{'link' => 'https://stackoverflow.com/'}, | |
{'link' => 'https://amazon.com/'}, | |
{'link' => 'http://canvas.instructure.com/'} | |
] | |
t1 = Time.now | |
case method | |
when :sync | |
sync_call(urls) | |
when :async | |
async_call(urls) | |
else | |
raise(ArgumentError, "timer method expected to be either :sync or :async") | |
end | |
t2 = Time.now | |
t2-t1 | |
end | |
def run_timer_loop(iterations, method) | |
(1..iterations).map { |i| print "#{i} "; timer(method)} | |
end | |
def average(times) | |
times.reduce(0) { |sum, delta| sum + delta } / times.count | |
end | |
N = 10 | |
average( run_timer_loop(N, :sync) ) | |
# => 1 2 3 4 5 6 7 8 9 10 => 6.4932305 | |
average( run_timer_loop(N, :async) ) | |
# => 1 2 3 4 5 6 7 8 9 10 => 1.5270557 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment