我有一个python列表的powerset生成器,我想使用multiprocessing模块对这些集合的元素进行一些计算。我的代码看起来像:
def powerset(seq):
'''Returns all the subsets of the list. This is a generator.'''
if len(seq) == 0:
yield seq
if len(seq) == 1:
yield seq
yield []
elif len(seq) > 1:
for item in powerset(seq[1:]):
yield [seq[0]]+item
yield item
def job(l):
# do some calculation with the list l
return do_some_hard_work(l)
def calculate():
pool_size = multiprocessing.cpu_count() * 2
pool = multiprocessing.Pool(processes=pool_size, maxtasksperchild=2)
pool_outputs = pool.map(job, powerset(list(range(1,10)))
pool.close()
pool.join()
return sum(pool_outputs)
问题是powerset函数是一个生成器,它将不起作用。但是我不能更换发电机,因为在生成孔功率集之前计算需要大量的时间和内存。有人知道我怎么解决这个问题吗?你知道吗
如果问题是您希望避免将整个powerset放在一个列表中,那么可以使用^{} ,它将一次使用迭代器
chunksize
元素,并将这些元素发送给工作进程,而不是将整个内容转换为一个列表并将其分块。你知道吗如果powerset非常大,则需要指定一个
chunksize
而不是默认值,即1:map
函数使用以下算法,让您了解一个好的大小:相关问题 更多 >
编程相关推荐