【问题标题】:Python Memory Leak with Struct and NumpyPython 内存泄漏与 Struct 和 Numpy
【发布时间】:2015-01-30 19:40:08
【问题描述】:

Python Memory Leak Using binascii, zlib, struct, and numpy 的延续,但示例代码正确说明了我遇到的问题。

import struct
import zlib
import binascii
import numpy as np
import os
import psutil
import gc

l = list()
l.append('eJztwYEAAAAAw6D5U1/gCFUB' + 'A'*161 + 'McA6vIAAQ==')
l.append('eJztwYEAAAAAw6D5U1/hAFUB' + 'A'*3957 + 'HwGw6IAAQ==')
l.append('eJztwYEAAAAAw6D5U1/hAFUB' + 'A'*3957 + 'LwGw6QAAQ==')

process = psutil.Process(os.getpid())
for s in l:
    print (process.get_memory_info()[0] / float(2 ** 20))
    byte_array = zlib.decompress(binascii.a2b_base64(s))
    array = np.array(struct.unpack('%dB' % (len(byte_array)), byte_array))
    del byte_array
    del array
    gc.collect()
    print (process.get_memory_info()[0] / float(2 ** 20))

del l
del s
gc.collect()
print (process.get_memory_info()[0] / float(2 ** 20))

打印出来:

22.37109375
25.83203125
25.83203125
95.65625
95.65625
166.69140625
166.69140625

为什么使用的内存不断增加?为什么即使在变量被删除之后,脚本末尾也会使用这么多内存?谢谢。

【问题讨论】:

    标签: python numpy memory-leaks struct


    【解决方案1】:

    这个链接http://bugs.python.org/issue14596 很有帮助。问题在于 struct 模块缓存格式字符串。如果我明确创建一个 Struct 对象,使用它,然后删除它,问题就消失了。

    import struct
    import zlib
    import binascii
    import os
    import psutil
    import gc
    
    
    def print_memory(string):
        print string + str(process.get_memory_info()[0] / float(2 ** 20))
    
    l = list()
    l.append('eJztwYEAAAAAw6D5U1/gCFUB' + 'A'*161 + 'McA6vIAAQ==')
    l.append('eJztwYEAAAAAw6D5U1/hAFUB' + 'A'*3957 + 'HwGw6IAAQ==')
    l.append('eJztwYEAAAAAw6D5U1/hAFUB' + 'A'*3957 + 'LwGw6QAAQ==')
    
    process = psutil.Process(os.getpid())
    for s in l:
        print_memory('Before inflating: ')
        byte_array = zlib.decompress(binascii.a2b_base64(s))
        _struct = struct.Struct('%dB' % (len(byte_array)))
        array = _struct.unpack(byte_array)
        del byte_array
        del array
        del _struct
        gc.collect()
        print_memory('After inflating and deleting: ')
    
    del l
    del s
    gc.collect()
    print_memory('After deleting everything: ')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-28
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 2017-10-18
      • 2013-03-08
      • 2011-11-28
      • 2012-12-02
      相关资源
      最近更新 更多