我需要实现该算法,以便利用多核处理器。 到目前为止我有这个:
def handle_primes(n, segments):
""" Returns the count of primes below n, using segments """
if __name__ == '__main__' :
# Initialize
count = 0
pool = Pool(processes=segments)
segment_size = n/segments
# Count primes in each segment
for start in xrange(2, n+1, segment_size+1):
end = start+segment_size
if end>n:
end = n
count += pool.apply_async(countprimes, [start, end]).get()
return count
countprimes()
计算从开始到限制的细分中的素数。
此代码比仅使用countprimes()
的常规实现运行得慢。
我是否错误地使用了多处理模块?
答案 0 :(得分:1)
get
会阻止。你需要写两个循环。试试这个:
# Count primes in each segment
processes = []
for start in xrange(2, n+1, segment_size+1):
end = start+segment_size
if end>n:
end = n
processes.append(pool.apply_async(countprimes, [start, end]))
for process in processes:
count += process.get()