首页 > 解决方案 > 运行 Python 多进程时性能逐渐下降

问题描述

我在多个案例中使用multiprocess. 刚启动程序的时候,我注意到运行速度是正常的:我使用 30 核在 5 分钟内可以得到大约 20-30 个输出,但是随着时间的推移,性能逐渐下降,例如,在某些时候,我只能在 30 分钟内得到 5 个输出。然后我杀死程序并重新运行它,然后它遵循相同的行为。可能是什么原因?是因为开销吗?我能做些什么?有关并行程序的示例代码,请参见以下内容:我正在代码中读取泡菜(类实例)

import multiprocess as mp
import os
import pickle

def run_all_cases(input_folder):
    pickle_files = [x for x in os.listdir(input_folder)]
    jobs = [(file, input_folder) for file in pickle_files]
    num_process = max(mp.cpu_count()-1, 1)
    with mp.Pool(processes=num_process) as pool:
        pool.starmap(run_single_case, jobs)

def run_single_case(file_name, input_folder):
    print(f"started {file} using {os.getpid()}")
    data = pickle.load(input_folder + file_name)
    # a complicated method in a class 
    data.run_some_method()
    pickle.dump(data, f"{file_name.split("_")[0]}_output.pkl")
    print(f"finished {file} using {os.getpid()}")


此外,当我打印出进程 ID 时,它正在超时更改。这是预期的(使用新进程 ID 启动 file_8)吗?输出类似于(如果使用 5 个内核):

started file_1 using core 8001
started file_2 using core 8002
started file_3 using core 8003
started file_4 using core 8004
started file_5 using core 8005
finished file_1 using core 8001
started file_6 using core 8001
finished file_2 using core 8002
started file_7 using core 8002
started file_8 using core 8006 #<-- it starts a new process id, rather than using the existing ones, is this expected?
finished file_3 using core 8003
...

==================================

更新:我深入探讨了一些在处理它们后进程已死的情况。当我运行单个实例时,一段时间后,在终端中它说:

zsh: killed     python3 test.py

我想这是问题所在:由于可能的内存问题(任何其他原因)而导致进程被终止,并且父进程没有启动新进程来继续运行作业,因此进程数量随着时间的推移而减少,因此我看到整体性能下降。

标签: pythonmultiprocess

解决方案


尝试杀死不再使用的旧的。它获得了一个新的进程 ID,因为多处理启动了新进程,而这些新进程将获得自己的进程 ID。在它运行时查看系统上所有正在运行的进程,看看你的 python 程序有多少实例正在运行,而你期望有多少。


推荐阅读