现在,在这两种情况下,执行时间都是相同的。我做错了什么?
以下是来源:
def time
start = Time.now
yield
p Time.now - start
end
range_limit = 9999
i_exponent = 9999
time do
array = (1 .. range_limit).map { |i | i**i_exponent }
p (array.inject(:+)/2)[0]
end
time do
first_thread = Thread.new do
arr = (1..range_limit/6).map { |i| i**i_exponent }
arr.inject(:+)
end
second_thread = Thread.new do
arr = (range_limit/6..range_limit*2/6).map { |i| i**i_exponent }
arr.inject(:+)
end
third_thread = Thread.new do
arr = (range_limit*2/6..range_limit*3/6).map { |i| i**i_exponent }
arr.inject(:+)
end
fourth_thread = Thread.new do
arr = (range_limit*3/6..range_limit*4/6).map { |i| i**i_exponent }
arr.inject(:+)
end
fifth_thread = Thread.new do
arr = (range_limit*4/6..range_limit*5/6).map { |i| i**i_exponent }
arr.inject(:+)
end
sixth_thread = Thread.new do
arr = (range_limit*5/6..range_limit).map { |i| i**i_exponent }
arr.inject(:+)
end
first_thread.join
second_thread.join
third_thread.join
fourth_thread.join
fifth_thread.join
sixth_thread.join
result = first_thread.value + second_thread.value + third_thread.value + fifth_thread.value + sixth_thread.value
p (result/2)[0]
end
答案 0 :(得分:1)
像Ruby和Python这样的解释器在执行多个线程时并不是真正的并行 - 为了保护解释器的状态,他们有一个global VM lock doesn't allow simultaneous execution。
为了获得线程的好处,您需要找到一种方法来执行在没有全局锁定的情况下运行的非Ruby代码use multiple processes而不是线程。另一种选择是切换到没有全局锁的ruby实现,例如JRuby或Rubinius。