我需要创建一个接受range
输入并应用一些操作的对象迭代器,以便创建素数的迭代器。然后,我需要将该素数迭代器传递给某个multiprocessing
方法(可能是imap
?),以便仅在调用对象迭代器时使用并行处理来评估素数。这是我的MWE:
import multiprocessing as mp
from itertools import islice
class PrimeIterator:
"""Iterator class"""
def __init__(self, input_stream, *, number_of_processes=mp.cpu_count()):
"""Initiate object"""
self.input = input_stream
self.pool = mp.Pool(number_of_processes)
def __iter__(self):
"""Return iterator"""
self.iterator = map(is_prime, self.input)
pool_iterator = self.pool.imap_unordered(pass_to_mp, self.iterator)
return pool_iterator
def __next__(self):
"""Return next item from iterator"""
try:
return next(pool_iterator)
except StopIteration:
return
def pass_to_mp(value):
time.sleep(.4)
return value
def is_prime(n):
if n < 2:
return False, n
elif n == 2:
return True, n
sqrt_n = int(n**0.5)+1
return len([i for i in range(2, sqrt_n+1) if n % i == 0]) == 0, n
PrimeIterator
可以像这样进行测试:
list(islice(PrimeIterator(range(100), number_of_processes=10), 10))
这是输出:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
尽管我收到正确的数据,但运行时间相当长。给定任务有更有效的multiprocesing
实现吗?