Python模块[医]铁线提供了对程序分配内存的详细了解。例如,一个用例是记录当前和峰值内存使用情况:
import tracemalloc
tracemalloc.start()
# ...code...
current, peak = tracemalloc.get_traced_memory()如果我们现在希望重置峰值,文档建议使用tracemalloc.reset_peak()。但是,这个函数只是在Python3.9中添加的,我想知道是否可以使用tracemalloc.clear_traces()实现同样的效果
我的用例是这样的:
for i in range(10):
# do sth
current, peak = tracemalloc.get_traced_memory()
print('Current and peak memory usage: {} {}'.format(current, peak))
# clear peak memory 因此,对于for -循环中的每一个i,我做了一些事情,并且只想测量我所创建的内容的内存。峰值应该只在每个指数,而不是在全球运行,这就是为什么我想清除它。
编辑:为了测试reset_peak()和clear_traces()之间的区别,我测试了这个程序:
tracemalloc.start()
current_memories = []
peak_memories = []
for i in range(10):
a = list(range(100000))
current, peak = tracemalloc.get_traced_memory()
current_memories.append(current/(1024*1024))
peak_memories.append(peak/(1024*1024))
tracemalloc.reset_peak()
# tracemalloc.clear_traces()
del current, peak
print('Average current memory [MB]: {}, average peak memory [MB]: {} +/- {}'.format(
round(np.mean(current_memories), 4), round(np.mean(peak_memories), 4),
round(np.std(peak_memories), 4))
)当我测试clear_traces()时,输出是:
Average current memory [MB]: 3.4273, average peak memory [MB]: 3.4274 +/- 0.0019当我使用reset_peak()时,我获得:
Average current memory [MB]: 3.4313, average peak memory [MB]: 6.5156 +/- 1.0273为什么这两种方法显示的内存量不同?
发布于 2021-12-29 23:39:02
在python3.9之前,模仿reset_peak似乎是不可能的。reset_peak是一个C函数,其代码是peak = current,内存计数器是C变量,因此不可能在python中修改它们。
对于clear_traces,所有以前的分配都被遗忘了:
>>> import tracemalloc
>>> tracemalloc.start()
>>> a = list(range(1000))
>>> tracemalloc.get_traced_memory()
(37619, 47929)
>>> tracemalloc.clear_traces()
>>> tracemalloc.get_traced_memory()
(8691, 19001)https://stackoverflow.com/questions/70525623
复制相似问题