Python - Sieve of Eratosthenes implementation for

2019-08-01 10:13发布

问题:

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() counts primes in a segment from start to limit.

This code runs slower than the regular implementation using just countprimes(). Am I using the multiprocessing module incorrectly?

回答1:

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()