Multiprocessing a for loop?

我有一个数组(称为 data_inputs) ,其中包含数百个天文图像文件的名称。然后这些图像被处理。我的代码可以工作,处理每个图像需要几秒钟。但是,它一次只能处理一个图像,因为我正在通过 for循环运行数组:

for name in data_inputs:
sci=fits.open(name+'.fits')
#image is manipulated

没有理由我必须在任何其他图像之前修改一个图像,所以是否有可能利用我的机器上的所有4个核心,每个核心运行在一个不同的图像上的 for 循环?

我已经阅读了关于 multiprocessing模块,但我不确定如何在我的情况下实现它。 I'm keen to get multiprocessing to work because eventually I'll have to run this on 10,000+ images.

197701 次浏览

你可以使用 multiprocessing.Pool:

from multiprocessing import Pool
class Engine(object):
def __init__(self, parameters):
self.parameters = parameters
def __call__(self, filename):
sci = fits.open(filename + '.fits')
manipulated = manipulate_image(sci, self.parameters)
return manipulated


try:
pool = Pool(8) # on 8 processors
engine = Engine(my_parameters)
data_outputs = pool.map(engine, data_inputs)
finally: # To make sure processes are closed in the end, even if errors happen
pool.close()
pool.join()

你可以简单地使用 multiprocessing.Pool:

from multiprocessing import Pool


def process_image(name):
sci=fits.open('{}.fits'.format(name))
<process>


if __name__ == '__main__':
pool = Pool()                         # Create a multiprocessing Pool
pool.map(process_image, data_inputs)  # process data_inputs iterable with pool

或者

with Pool() as pool:
pool.map(fits.open, [name + '.fits' for name in datainput])

如果只使用 for循环来迭代一个可迭代文件,我建议使用 imap_unorderedchunksize。它将在计算每个循环的结果时立即返回这些结果。map等待所有结果被计算,因此被阻塞。