python - 如何获取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'
不是实际变量a
and b
。
是否有任何替代方法来获取所有局部变量的大小,或者可以对程序进行任何修改以获取所有局部变量的大小?
该程序也有不正确的输出
解决方案
您应该使用list_of_locals = locals().values()
- 您当前正在获取局部变量名称列表,这将获得值,这正是您想要的。
推荐阅读
- typescript - Cloud Function 在 android 应用程序上返回 null
- xodus - Xodus 实体商店可以共享交易吗?
- ios - 即使在后台并且如果应用程序在 Swift 中被终止,计时器也会继续执行
- python - 如何在python的数据框中查找具有相同值的列列表
- node.js - 为什么我收到 Aurelia 和 Gulp 的打字稿编译错误?
- estimation - 估计平均参数
- git - git compare 没有显示任何差异
- php - 使用动态类
- java - 程序仅以特定值进入无限循环
- android - 如何在Android应用程序中多次单击按钮并更改模式