簡體   English   中英

如何在python中並行化一個簡單的循環?

[英]How do I parallelize a simple loop in python?

我有一個循環,每次都崩潰我的RAM,我想並行化。

我嘗試了這段代碼,但是沒有用:

from joblib import Parallel, delayed

from Bio.Align.Applications import ClustalOmegaCommandline


def run(test):
    im = process_image(Image.open(test['Path'][i]))
    test_images.append(im)


if __name__ == "__main__":
    test_images = []
    test = range(len(test))

    Parallel(n_jobs=len(test)(
        delayed(run)(i) for i in len(test))

我收到了這個錯誤:

文件“”,第16行延遲(運行)(i)for i in len(test))^ SyntaxError:解析時意外的EOF

我的循環:

test_images = []
for i in range(len(test)):
  im = process_image(Image.open(test['Path'][i]))
  test_images.append(im)
test_images = np.asarray(test_images)

我嘗試了幾種解決方案,但我需要一個數據庫輸出。

你能嘗試以下方法嗎?

def process_image(img_path):
    img_obj = Image.open(img_path)
    # your logic here
    return im

def main():
    image_dict = {}
    with concurrent.futures.ProcessPoolExecutor() as executor:
        for img_path, im in zip(test['Path'], executor.map(process_image, test['Path'])):
            image_dict[img_path] = im
    return image_dict

if __name__ == '__main__':
    image_dict = main()
    test_images = np.asarray(image_dict.values())

我不確定,並行化是否是內存問題的答案。

您是否需要將每個圖像存儲在列表中,該列表存儲在內存中? 也許只需保存路徑並在需要時加載它?

或試試發電機 這些值是惰性生成的(只有在需要時才會生成),從而減少內存消耗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM