numpy Python中变量的大小[重复]

sqyvllje  于 2023-05-22  发布在  Python
关注(0)|答案(3)|浏览(131)

此问题已在此处有答案

How do I determine the size of an object in Python?(16个答案)
Size of a Python list in memory(4个答案)
4天前关闭。
我想知道一个变量占用了多少内存。
让我们假设这个例子:

import numpy as np

t = [np.random.rand(10000) for _ in range(1000)]

t占用多少兆内存?
我跑过去:
sys.getsizeof(array_list)
我得到的是8856,相对于t中包含的信息量,它似乎很低
最好的问候。

6g8kf2rb

6g8kf2rb1#

from pympler import asizeof
asizeof.asizeof([np.random.rand(10000) for _ in range(1000)])

#output
80120872

链接:https://pypi.org/project/Pympler/

pip install Pympler
1zmg4dgp

1zmg4dgp2#

我想这(不求助于外部库)可以做到这一点:

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
nzk0hqpo

nzk0hqpo3#

简答:sys.getsizeof(variable)
示例:

import sys
integer = 10
print("The size of the integer variable is:",sys.getsizeof(integer), "bytes.")

Full answer

相关问题