Multiprocessing a for loop?(多处理一个for循环?)
问题描述
我有一个数组(称为 data_inputs),其中包含数百个天文图像文件的名称.然后对这些图像进行处理.我的代码有效,并且需要几秒钟来处理每个图像.但是,它一次只能做一个图像,因为我正在通过 for 循环运行数组:
I have an array (called data_inputs) containing the names of hundreds of astronomy images files. These images are then manipulated. My code works and takes a few seconds to process each image. However, it can only do one image at a time because I'm running the array through a for loop:
for name in data_inputs:
sci=fits.open(name+'.fits')
#image is manipulated
没有理由我必须先修改图像,所以是否可以利用我机器上的所有 4 个核心,每个核心在不同的图像上通过 for 循环运行?
There is no reason why I have to modify an image before any other, so is it possible to utilise all 4 cores on my machine with each core running through the for loop on a different image?
我已阅读有关 multiprocessing 模块的信息,但我不确定如何在我的情况下实现它.我热衷于让 multiprocessing 工作,因为最终我必须在 10,000 多张图像上运行它.
I've read about the multiprocessing module but I'm unsure how to implement it in my case.
I'm keen to get multiprocessing to work because eventually I'll have to run this on 10,000+ images.
推荐答案
你可以简单地使用 multiprocessing.Pool:
You can simply use 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
这篇关于多处理一个for循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:多处理一个for循环?
基础教程推荐
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
