python-3.x tracemalloc会从最近的快照中删除释放的内存吗?

myzjeezk  于 2023-01-27  发布在  Python
关注(0)|答案(1)|浏览(100)

我正在调试一个Python with Flask应用程序,内存会随时间增长。
我知道tracemalloc跟踪Python分配的内存,它在每个快照中向我显示了程序中分配的内存的回溯。
我的问题是,最近的快照是否显示了已分配内存的历史数据,或者它是否显示了已分配但尚未释放的内存。
我在程序中增加内存后拍摄了tracemalloc快照

dgtucam1

dgtucam11#

根据我所做的测试,tracemalloc似乎不跟踪释放的内存。

import tracemalloc
import gc
tracemalloc.start(1)
y = None

def dump_tracemalloc_snapshot():
        gc.collect()
        snapshot = tracemalloc.take_snapshot()
        stats = snapshot.statistics('traceback')
        for stat in stats[:3]:
            print("%s memory blocks: %.1f KiB" % (stat.count, stat.size / 1024))

            for line in stat.traceback.format():
                print(line)

        print('\n\n')        

def allocate_memory():
    global y
    x = []
    for i in range(100000):
        x.append(f"AAA{i}")
    y = x

if __name__=="__main__":
    allocate_memory()
    
    dump_tracemalloc_snapshot()
    del y 
    dump_tracemalloc_snapshot()

输出:

100001 memory blocks: 6337.7 KiB
  File "/Users/jafar.atili/Code/tracemalloc_parser/file.py", line 23
    x.append(f"AAA{i}")
1 memory blocks: 0.1 KiB
  File "/Users/jafar.atili/Code/tracemalloc_parser/file.py", line 19
    def allocate_memory():
1 memory blocks: 0.1 KiB
  File "/Users/jafar.atili/Code/tracemalloc_parser/file.py", line 6
    def dump_tracemalloc_snapshot():


26 memory blocks: 2.1 KiB
  File "/opt/homebrew/Cellar/python@3.11/3.11.1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/linecache.py", line 137
    lines = fp.readlines()
2 memory blocks: 0.2 KiB
  File "/opt/homebrew/Cellar/python@3.11/3.11.1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/linecache.py", line 143
    cache[filename] = size, mtime, lines, fullname
1 memory blocks: 0.1 KiB
  File "/Users/jafar.atili/Code/tracemalloc_parser/file.py", line 19
    def allocate_memory():

相关问题