1

我需要实现该算法,以便它利用多核处理器。到目前为止,我有这个:

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()从开始到限制计算段中的素数。

此代码运行速度比使用 just 的常规实现要慢countprimes()。我是否错误地使用了多处理模块?

4

1 回答 1

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()
于 2013-06-02T22:20:03.230 回答