gpt4 book ai didi

python - 迭代 pool.imap_unordered

转载 作者:太空狗 更新时间:2023-10-30 01:03:16 24 4
gpt4 key购买 nike

考虑非常简单的代码:

#!/usr/bin/python

from multiprocessing import Pool
import random

def f(x):
return x*x

def sampleiter(n):
num = 0
while num < n:
rand = random.random()
yield rand
num += 1

if __name__ == '__main__':
pool = Pool(processes=4) # start 4 worker processes
for item in pool.imap_unordered(f, sampleiter(100000000000000), 20):
print item
pool.close

在终端运行时,Python 内存泄漏。
有什么问题吗?

最佳答案

输出缓冲不是问题(或者至少不是唯一的问题),因为 (a) Python 进程本身在内存中增长,并且 (b) 如果您重定向到 /dev/null 它仍然会发生。

我认为问题在于,当您打印出结果时,池返回结果的速度比它们被消耗的速度快得多,因此大量结果都在内存中。如果你看the source of the class that does this ,中间结果存储在名为_itemscollections.deque中;我敢打赌 _items 会越来越大。

不过,我不确定如何测试它,因为即使 imap_unordered returns an instance of this class您似乎仍然只能使用生成器方法:

In [8]: r = pool.imap_unordered(f, sampleiter(1e8), 20)

In [9]: print dir(r)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__',
'__init__', '__iter__', '__name__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'close', 'gi_code', 'gi_frame', 'gi_running', 'next', 'send', 'throw']

更新:如果您将time.sleep(.01) 添加到f(),内存使用将保持完全不变。所以,是的,问题是您产生结果的速度比使用它们的速度快。

(顺便说一句:您的意思是代码示例末尾的 pool.close()pool.close 只是对该函数的引用,并不'实际上并没有调用它。)

关于python - 迭代 pool.imap_unordered,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9862091/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com