我写了一个测试程序。简而言之,它执行以下操作:
- 在单线程中执行一些随机无用的计算(但足够长)并打印执行时间
- 在 6 个线程中执行相同的程序并打印执行时间
现在,在这两种情况下,执行时间是相同的。我究竟做错了什么?
以下是来源:
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