首页 > 解决方案 > 如何获取python中每个局部变量的大小?

问题描述

我在这里提到了堆栈溢出问题,它表明使用getsizeof()函数来获取变量的大小(以字节为单位的内存)。

我现在的问题是,我们如何才能获得程序中所有局部变量的大小?(假设我们有大量的局部变量)。

目前,我已经尝试了以下程序;

import numpy as np
from sys import getsizeof

a = 5
b = np.ones((5,5))

print("Size of a:", getsizeof(a))
print("Size of b:", getsizeof(b))

list_of_locals = locals().keys()

### list_of_locals contains the variable names
for var in list(list_of_locals):
    print("variable {} has size {}".format(var,getsizeof(var)))

它有一个输出:

Size of a: 28
Size of b: 312
variable __name__ has size 57
variable __doc__ has size 56
variable __package__ has size 60
variable __loader__ has size 59
variable __spec__ has size 57
variable __annotations__ has size 64
variable __builtins__ has size 61
variable __file__ has size 57
variable __cached__ has size 59
variable np has size 51
variable getsizeof has size 58
variable a has size 50
variable b has size 50

, 的输入getsizeof(obj)应该是一个对象。在这种情况下,它原来是字符'a''b'不是实际变量aand b

是否有任何替代方法来获取所有局部变量的大小,或者可以对程序进行任何修改以获取所有局部变量的大小?

该程序也有不正确的输出

标签: python

解决方案


您应该使用list_of_locals = locals().values()- 您当前正在获取局部变量名称列表,这将获得值,这正是您想要的。


推荐阅读