在Python中变量的大小

huangapple go评论77阅读模式
英文:

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.")

Full answer

英文:

Short answer: sys.getsizeof(variable)

Example:

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

Full answer

huangapple
  • 本文由 发表于 2023年5月17日 23:01:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273511.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定