英文:
size of variable in python
问题
我想知道一个变量占用了多少内存。
让我们假设这个例子:
import numpy as np
t = [np.random.rand(10000) for _ in range(1000)]
变量 t
占用多少兆字节的内存?
我运行了:
sys.getsizeof(array_list)
我得到了 8856
,这似乎对于 t
中包含的信息量来说很低。
最好的问候。
英文:
I would like to know how much memory is being occupied by a variable.
Let us assume this example:
import numpy as np
t = [np.random.rand(10000) for _ in range(1000)]
How much memory in megabytes is t
occupying?
I ran:
sys.getsizeof(array_list)
and I am getting 8856
which seems low for the amount of information contained in t
Best Regards.
答案1
得分: 3
Link: https://pypi.org/project/Pympler/
pip install Pympler
英文:
from pympler import asizeof
asizeof.asizeof([np.random.rand(10000) for _ in range(1000)])
#output
80120872
Link : https://pypi.org/project/Pympler/
pip install Pympler
答案2
得分: 1
我猜这个(不依赖外部库)可以完成任务:
def deepgso(ob):
size = sys.getsizeof(ob)
if isinstance(ob, (list,tuple,set)):
for element in ob:
size+=deepgso(element)
if isinstance(ob, dict):
for k,v in ob.items():
size+=deepgso(k)
size+=deepgso(v)
return size
英文:
I guess this (without resorting to external libraries) does the trick:
def deepgso(ob):
size = sys.getsizeof(ob)
if isinstance(ob, (list,tuple,set)):
for element in ob:
size+=deepgso(element)
if isinstance(ob, dict):
for k,v in ob.items():
size+=deepgso(k)
size+=deepgso(v)
return size
答案3
得分: -1
Short answer: sys.getsizeof(variable)
Example:
import sys
integer = 10
print("The size of the integer variable is:", sys.getsizeof(integer), "bytes.")
英文:
Short answer: sys.getsizeof(variable)
Example:
import sys
integer = 10
print("The size of the integer variable is:",sys.getsizeof(integer), "bytes.")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论