Skip to content

Instantly share code, notes, and snippets.

@maxjustus
Created November 11, 2011 15:59
Show Gist options
  • Save maxjustus/1358356 to your computer and use it in GitHub Desktop.
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
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