My first question is about SO, but I have been hiding for a long time, so you have to forgive me if I break any rules or post a garbage question.
I'm trying to better understand the flows, and I decided to test the MRI and see how it works in general.
Given the following code (and output), why are multithreaded operations much slower than the non-threaded version?
code
class Benchmarker
def self.go
puts '----------Benchmark Start----------'
start_t = Time.now
yield
end_t = Time.now
puts "Operation Took: #{end_t - start_t} seconds"
puts '----------Benchmark End------------'
end
end
puts 'Benchmark 1 (threaded, mutex):'
Benchmarker.go do
array = []
mutex = Mutex.new
5000.times.map do
Thread.new do
mutex.synchronize do
1000.times do
array << nil
end
end
end
end.each(&:join)
puts array.size
end
puts 'Benchmark 2 (threaded, no mutex):'
Benchmarker.go do
array = []
5000.times.map do
Thread.new do
1000.times do
array << nil
end
end
end.each(&:join)
puts array.size
end
puts 'Benchmark 3 (no threads):'
Benchmarker.go do
array = []
5000.times.map do
1000.times do
array << nil
end
end
puts array.size
end
output
Benchmark 1 (threaded, mutex):
5000000
Operation Took: 3.373886 seconds
Benchmark 2 (threaded, no mutex):
5000000
Operation Took: 5.040501 seconds
Benchmark 3 (no threads):
5000000
Operation Took: 0.454665 seconds
Thanks in advance.
source
share