【发布时间】:2016-07-04 05:00:18
【问题描述】:
我正在尝试减少我的 python 3 代码的内存需求。现在,for 循环的每次迭代都需要比上一次更多的内存。
我写了一小段与我的项目具有相同行为的代码:
import numpy as np
from multiprocessing import Pool
from itertools import repeat
def simulation(steps, y): # the function that starts the parallel execution of f()
pool = Pool(processes=8, maxtasksperchild=int(steps/8))
results = pool.starmap(f, zip(range(steps), repeat(y)), chunksize=int(steps/8))
pool.close()
return results
def f(steps, y): # steps is used as a counter. My code doesn't need it.
a, b = np.random.random(2)
return y*a, y*b
def main():
steps = 2**20 # amount of times a random sample is taken
y = np.ones(5) # dummy variable to show that the next iteration of the code depends on the previous one
total_results = np.zeros((0,2))
for i in range(5):
results = simulation(steps, y[i-1])
y[i] = results[0][0]
total_results = np.vstack((total_results, results))
print(total_results, y)
if __name__ == "__main__":
main()
对于 for 循环的每次迭代,simulation() 中的每个线程的内存使用量都等于我的代码使用的总内存量。
每次运行并行进程时,Python 是否会克隆我的整个环境,包括 f() 不需要的变量?如何防止这种行为?
理想情况下,我希望我的代码只复制执行 f() 所需的内存,而我可以将结果保存在内存中。
【问题讨论】:
-
是的,它克隆了程序的整个上下文
-
你应该至少用
if __name__ == '__main__':保护那些主要操作。 -
@snakecharmerb results[0][0] 只是一个浮点数。
-
@Ilja 是的,好点。我在我的真实代码中执行此操作,但我认为对于此示例,它不是必需的。我会插入它(但它不会改变行为)。
-
@Isea 编辑后我可以观察到您描述的行为。
标签: python memory python-multiprocessing