【问题标题】:How to get the size of each local variable in python?如何获取python中每个局部变量的大小?
【发布时间】:2020-08-21 19:18:36
【问题描述】:

我提到了堆栈溢出问题here,它表示使用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' 而不是实际变量 ab

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

程序也有错误的输出

【问题讨论】:

  • 您如何定义“本地”?您显示的代码实际上是检查所有 globals (因为您不在函数定义中,所以没有本地范围,只有模块的全局范围,这是 locals() 返回的内容)。
  • 嗯,你是对的,这里的 locals() 显示全局范围内的变量,因为它们是相同的。我的目的是获得变量的大小。好吧,即使我把这些内容移到一个函数里面,问题依然存在。

标签: python


【解决方案1】:

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

【讨论】:

  • 嗯,已经接近解决方案了。我用过:print("variable {} has size {}".format(var,getsizeof(locals()[var])))
猜你喜欢
  • 1970-01-01
  • 2015-07-12
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
  • 2020-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多