Last active
December 12, 2015 05:18
-
-
Save phyous/4720240 to your computer and use it in GitHub Desktop.
Multi-threading example 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
num_iterations = 20 | |
num_threads = 4 | |
# Try counting to 1 million on 4 separate threads 20 times | |
total_time = 0.0 | |
num_iterations.times do |iter| | |
threads = [] | |
t_0 = Time.now | |
for i in 1..num_threads | |
threads << Thread.new(i) { |t| | |
count = 0 | |
1000000.times do | |
count += 1 | |
end | |
} | |
end | |
# Wait for all threads to complete | |
threads.each { |thread| thread.join } | |
t_1 = Time.now | |
time_ms = (t_1-t_0) * 1000 | |
puts "TEST #{iter}: Time elapsed = #{time_ms}ms" | |
total_time += time_ms | |
end | |
puts "Average completion time: #{total_time/num_iterations}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment