I'm attempting to write a multi-threaded solution for Project Euler's problem 14, but I'm not really seeing a speed up. There isn't any shared resources and no Mutex locks are being used... Is my code slow because of context switches? Am I not correctly understanding the benefit of threads?
http://projecteuler.net/problem=14
require 'benchmark'
benchmark_results = Benchmark.measure do
threads = []
num_threads = 10
num_threads.times do |thread_num|
threads << Thread.new(thread_num + 1) do |thread_num|
Thread.current["max_length"] = 0
(thread_num..1000000).step(num_threads).each do |i|
next if i.even?
current = i
length = 0
until current == 1
if current.even?
current = current / 2
else
current = current * 3 + 1
end
length += 1
end
if length > Thread.current["max_length"]
Thread.current["max_length"] = length
Thread.current["max_i"] = i
end
end
end
end
threads.each { |thread| thread.join; print "#{thread['max_i']} -> #{thread['max_length']}\n" }
end
puts benchmark_results