我需要实现该算法,以便它能够利用多核处理器。到目前为止我有这个:
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()
的常规实现要慢。我是否错误地使用了多处理模块?
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()
我是一名优秀的程序员,十分优秀!