python - 列出内存使用情况

标签 python list memory

我正在尝试改善 python 脚本的内存使用情况,因此我需要知道列表的 RAM 使用情况。 我用

测量内存使用情况
print str(sys.getsizeof(my_list)/1024/1024)

希望能给我 RAM 中列表的大小(以 Mb 为单位)。

它输出 12 Mb,但是在 top 命令中,我看到我的脚本在运行时使用了 4G 笔记本电脑 RAM 的 70%。

此外,此列表应包含 ~500Mb 文件的内容。

所以 12Mb 是不现实的。

如何测量实际内存使用情况?

最佳答案

sys.getsizeof 仅考虑列表本身,而不考虑它包含的项目。

根据sys.getsizeof documentation :

... Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to. ...

使用Pympler :

>>> import sys
>>> from pympler.asizeof import asizeof
>>>
>>> obj = [1, 2, (3, 4), 'text']
>>> sys.getsizeof(obj)
48
>>> asizeof(obj)
176

注意:大小以字节为单位。

关于python - 列出内存使用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55895080/

相关文章:

python - Django-registration and ReCaptcha integration - 如何传递用户的IP

python - 为元组数组定义堆键

python - 关于简单python脚本的问题

list - 惰性求值步骤: filtering a list

如果需要多个标准输入,python asyncio 会死锁

python - 在二维矩阵中找出相同颜色的 block

python - 为什么在 Cython 中将列表转换为集合不起作用?

ios - GLKit 内存泄漏 copywithZone

C++ 结构数组和相等数组之间的区别

Javascript + Knockout.js 内存泄漏 - 如何确保对象被销毁?