![](/img/trans.png)
[英]How to prevent a function from adding repeated keys to a dictionary in python
[英]Prevent RAM space from filling from repeated Python function
我在下面有一个 Python function 示例,它简单地接受一个变量并在返回之前对其执行简单的数学运算。
If I parallelise this function, to better reflect the operation I would like to do in real life, and run the parallelised function 10 times, I notice on my IDE that the memory increases despite using the del results
line.
import multiprocessing as mp
import numpy as np
from tqdm import tqdm
def function(x):
return x*2
test_array = np.arange(0,1e4,1)
for i in range(10):
pool = mp.Pool(processes=4)
results = list(tqdm(pool.imap(function,test_array),total=len(test_array)))
results = [x for x in results if str(x) != 'nan']
del results
我有几个问题,如果知道答案,我将不胜感激:
pool.imap 创建的每个新进程都需要接收有关 function 及其应用 function 的元素的一些信息。 此信息是副本,因此将导致信息成为副本。
如果你想减少它,你可能想看看 pool.imap 的 chunksize 参数。
另一种方法是仅依赖 numpy 中的函数。 你现在可能已经,但你可以做results = test_array * 2
。 我不知道您的真实示例如何,但您可能不需要使用 Python 的池。
此外,如果您打算实际编写快速代码,请不要使用 tqdm。 这很好,如果你需要它,你需要它,但它会减慢你的代码。
我还没有尝试过,但我很确定你不需要定义
pool= mp.Pool(processes=4)
在循环中,您无缘无故地启动了 10 个池实例。 也许尝试将其移出并查看您的 memory 使用量是否减少?
如果这没有帮助,请考虑重组代码以利用yield
来防止 memory 填满。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.