Skip to main content
 首页 » 编程设计

python之使用多处理迭代幂集

2025年05月04日8oomusou

我有一个用于 python 列表幂集的生成器,我想使用多处理模块对这些集合的元素进行一些计算。我的代码如下所示:

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-function 是一个生成器,它不会工作。但是我不能更换生成器,因为在计算之前生成孔动力集需要很多时间和内存。有谁知道我该如何解决这个问题?

请您参考如下方法:

如果问题是您不想将整个电源组放在一个列表中,您可以使用 pool.imap ,它将一次消耗您的迭代器 chunksize 元素,并将它们发送给工作进程,而不是将整个事物转换为列表并将其分块。

pool_size = multiprocessing.cpu_count() * 2 
pool = multiprocessing.Pool(processes=pool_size, maxtasksperchild=2) 
pool_outputs = pool.imap(job, powerset(list(range(1,10))), chunksize=<some chunksize>) 
pool.close() 
pool.join() 

如果您的 powerset 非常大,您需要指定一个 chunksize 而不是默认值,即 1:

The chunksize argument is the same as the one used by the map() method. For very long iterables using a large value for chunksize can make the job complete much faster than using the default value of 1.

map 函数使用以下算法,让您了解合适的大小:

chunksize, extra = divmod(len(iterable), len(pool_size) * 4) 
if extra: 
    chunksize += 1