本文介绍了Python-用于多处理环境的Eratosthenes实现筛的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要实现该算法,以便它利用多核处理器的优势.到目前为止,我有这个:
I need to implement the algorithm so it takes advantage of multicore processors.So far i have this:
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()
counts primes in a segment from start to limit.
此代码比仅使用countprimes()
的常规实现运行慢.我是否错误地使用了多处理模块?
This code runs slower than the regular implementation using just countprimes()
.Am I using the multiprocessing module incorrectly?
推荐答案
get
将被阻止.您需要编写两个循环.试试这个:
The get
will block. You need to write two loops. Try this:
# 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()
这篇关于Python-用于多处理环境的Eratosthenes实现筛的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!