Last active
March 15, 2023 11:34
-
-
Save benoittgt/44a78c43b4f2d5cb8aa0dd999028fa83 to your computer and use it in GitHub Desktop.
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 'gvl-tracing' | |
require 'net/http' | |
class ThreadPool | |
def initialize(size) | |
@size = size | |
@jobs = Queue.new # FIFO https://rubyapi.org/3.2/o/thread/queue | |
@pool = Array.new(@size) do |i| | |
Thread.new do | |
catch(:exit) do | |
loop do | |
job = @jobs.pop | |
job.call | |
end | |
end | |
end | |
end | |
end | |
def schedule(&block) | |
@jobs << block | |
end | |
def run | |
@size.times do | |
schedule { throw :exit } | |
end | |
@pool.map(&:join) | |
end | |
end | |
def timer(type) | |
puts ">> Start #{type}" | |
# GvlTracing.start("tracing-#{type}.json") | |
start = Time.now | |
yield | |
p Time.now - start | |
# GvlTracing.stop | |
sleep 2 | |
end | |
COUNT = 50 | |
timer('without_thread') do | |
COUNT.times do | |
Net::HTTP.get(URI('https://api.github.com/octocat')) | |
end | |
end | |
timer('with_thread') do | |
threads = [] | |
COUNT.times do | |
threads << Thread.new do | |
Net::HTTP.get(URI('https://api.github.com/octocat')) | |
end | |
end | |
threads.map(&:join) | |
end | |
timer('with_thread_pooling') do | |
pool = ThreadPool.new(25) | |
COUNT.times do | |
pool.schedule do | |
Net::HTTP.get(URI('https://api.github.com/octocat')) | |
end | |
end | |
pool.run | |
end | |
=begin | |
>> Start without_thread | |
5.857929 | |
>> Start with_thread | |
0.472429 | |
>> Start with_thread_pooling | |
0.494334 | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment