实现思路
- 安装工具:使用
memory_profiler
和 pympler
库,memory_profiler
用于逐行分析函数内存使用情况,pympler
用于更全面分析复杂数据结构。
- 使用
memory_profiler
:装饰目标函数,查看函数执行时内存使用变化。
- 使用
pympler
:
asizeof
函数获取对象及其子对象的内存占用。
muppy
获取所有活动对象,summarize
总结对象信息,print_(summary)
打印总结信息,辅助找出内存占用大的对象。
关键代码片段
from memory_profiler import profile
from pympler import asizeof, muppy
class CustomClass:
pass
nested_dict = {
'key1': [1, 2, 3],
'key2': {'sub_key':'sub_value'},
'key3': CustomClass()
}
@profile
def process_nested_dict(d):
# 对字典进行一些操作,例如遍历
for key, value in d.items():
if isinstance(value, list):
for item in value:
pass
elif isinstance(value, dict):
for sub_key, sub_value in value.items():
pass
process_nested_dict(nested_dict)
# 使用 pympler 分析
objects = muppy.get_objects()
summary = muppy.summarize(objects)
print(summary)
print('Total size of nested_dict:', asizeof.asizeof(nested_dict))