Skip to content

Instantly share code, notes, and snippets.

@phyous
Last active December 12, 2015 05:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phyous/4720240 to your computer and use it in GitHub Desktop.
Save phyous/4720240 to your computer and use it in GitHub Desktop.
Multi-threading example in ruby.
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