Last active
November 4, 2021 08:06
-
-
Save romiras/be37a75411ad39a2853f92540746997c to your computer and use it in GitHub Desktop.
Workers with Concurrent::Future in Ruby
This file contains 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 'concurrent' | |
require 'benchmark' | |
max = 20 # number of tasks to process | |
n_workers = 4 # number of concurrent workers | |
results = [] # | |
lambda = -> (iter, i) { results << ('%04d' % i); d = rand(0.005)+0.001; puts("Iteration #{iter}. sleep %.3f" % d); sleep(d) } | |
workers = Array.new(n_workers, lambda) | |
iter = 0 | |
(max / n_workers).times do |v| | |
iter += 1 | |
t = Benchmark.realtime do | |
workers.map do |executor| | |
Concurrent::Future.execute { executor.call(iter, v) } | |
end.map(&:value) | |
end | |
puts "Elapsed %.3f" % t | |
end | |
p results |
This file contains 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
Iteration 1. sleep 0.328 | |
Iteration 1. sleep 0.883 | |
Iteration 1. sleep 0.553 | |
Iteration 1. sleep 0.017 | |
Elapsed 0.884 | |
Iteration 2. sleep 0.556 | |
Iteration 2. sleep 0.262 | |
Iteration 2. sleep 0.092 | |
Iteration 2. sleep 0.326 | |
Elapsed 0.557 | |
Iteration 3. sleep 0.768Iteration 3. sleep 0.611 | |
Iteration 3. sleep 0.149 | |
Iteration 3. sleep 0.036 | |
Elapsed 0.769 | |
Iteration 4. sleep 0.299 | |
Iteration 4. sleep 0.194 | |
Iteration 4. sleep 0.465 | |
Iteration 4. sleep 0.821 | |
Elapsed 0.823 | |
Iteration 5. sleep 0.308 | |
Iteration 5. sleep 0.636 | |
Iteration 5. sleep 0.694Iteration 5. sleep 0.554 | |
Elapsed 0.696 | |
["0000", "0000", "0000", "0000", "0001", "0001", "0001", "0001", "0002", "0002", "0002", "0002", "0003", "0003", "0003", "0003", "0004", "0004", "0004", "0004"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment