Created
November 11, 2011 15:59
-
-
Save maxjustus/1358356 to your computer and use it in GitHub Desktop.
Parallelize a certain section of code and yield the result to a block
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 'benchmark' | |
require 'net/http' | |
require 'uri' | |
thrs = [] | |
url = URI.parse('http://yahoo.com') | |
class Parayield | |
attr_accessor :threads | |
def initialize | |
@threads = [] | |
end | |
def parallel_yield(request_proc, &blk) | |
threads <<[blk, Thread.new do | |
Thread.current[:result] = request_proc.call | |
end] | |
end | |
def join | |
threads.each do |request_proc, thread| | |
thread.join | |
request_proc.call(thread[:result]) | |
end | |
end | |
end | |
t = Benchmark.measure do | |
pyld = Parayield.new | |
100.times do |i| | |
pyld.parallel_yield(->() { Net::HTTP.get_response(url) }) do |r| | |
p "#{i} got #{r}" | |
end | |
end | |
pyld.join | |
end | |
puts t | |
t = Benchmark.measure do | |
100.times do | |
p Net::HTTP.get_response(url) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment