Yts*_*oer 4 memory-leaks python-3.6
我正在尝试追查 python 3.6 程序中的内存泄漏。
为此,我正在测试tracemalloc,它允许我比较内存快照并打印出“回溯”。
tracemalloc.start()根据文档,回溯中的最大帧数应设置为第一个参数。
然而,在我的最小测试设置(下面的代码)中,我使用参数 25 启动tracemalloc,但我在回溯中只得到 1 帧,而我期望的是 2 帧:
me@my_machine:/tmp$ python ./test_tm.py
Entry: /tmp/test_tm_utils.py:2: size=3533 KiB (+3533 KiB), count=99746 (+99746), average=36 B
Traceback:
/tmp/test_tm_utils.py:2
Run Code Online (Sandbox Code Playgroud)
我期望有两行,如下所示:
Entry: /tmp/test_tm_utils.py:2: size=3533 KiB (+3533 KiB), count=99746 (+99746), average=36 B
Traceback:
/tmp/test_tm_utils.py:2
/tmp/test_tm.py:10
^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
主程序在_/tmp/test_tm.py_中:
import tracemalloc
tracemalloc.start(25)
import test_tm_utils
if __name__ == '__main__':
s1 = tracemalloc.take_snapshot()
test_tm_utils.myfun()
s2 = tracemalloc.take_snapshot()
diff = s2.compare_to(s1, 'lineno')
for entry in diff[:1]:
print('\nEntry: {}'.format(entry))
print('Traceback:')
for line in entry.traceback:
print(' {}'.format(line))
Run Code Online (Sandbox Code Playgroud)
以及内存泄漏函数test_tm_utils.py:
def myfun(lst=list()):
lst.append([i for i in range(100000)])
Run Code Online (Sandbox Code Playgroud)
小智 5
秘密是 key_type 参数。您必须使用该值"traceback"来获取 中指定的所有行tracemalloc.start()。如果你使用"lineno"或者"filename"你只得到一根线。
对于统计数据或您的情况compare_to都是如此。
所以你的代码应该是这样的:
s2 = tracemalloc.take_snapshot()
diff = s2.compare_to(s1, 'traceback') # This is the only change
for entry in diff[:1]:
print('\nEntry: {}'.format(entry))
print('Traceback:')
for line in entry.traceback:
print(' {}'.format(line))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1048 次 |
| 最近记录: |