2013-06-02 112 views
1

我需要實現算法,以便利用多核處理器。 到目前爲止,我有這樣的:Python - 用於多處理環境的Eratosthenes實現的篩選

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

你用什麼'n's測試代碼? – Elazar

回答

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