为什么两个阵列具有不同的内存大小?

时间:2019-08-23 12:04:57

标签: python python-3.x numpy numpy-ndarray

我正在使用numpy.array处理一个大矩阵(大约20000 * 20000),我在探索数组的内存使用时遇到了一个问题。

>>> a = np.random.random((5,5))
>>> np.savetxt(fname = path, X = a)
>>> b = np.loadtxt(fname = path)
>>> b
array([[0.17940875, 0.33674265, 0.14397669, 0.49947964, 0.70878022],
       [0.88072205, 0.69542991, 0.6094819 , 0.47855311, 0.73319366],
       [0.75855104, 0.79885525, 0.77966685, 0.3756036 , 0.81272082],
       [0.754227  , 0.07242963, 0.16935453, 0.76840836, 0.10537832],
       [0.74316004, 0.76265098, 0.7661815 , 0.22217968, 0.32509482]])
>>> a
array([[0.17940875, 0.33674265, 0.14397669, 0.49947964, 0.70878022],
       [0.88072205, 0.69542991, 0.6094819 , 0.47855311, 0.73319366],
       [0.75855104, 0.79885525, 0.77966685, 0.3756036 , 0.81272082],
       [0.754227  , 0.07242963, 0.16935453, 0.76840836, 0.10537832],
       [0.74316004, 0.76265098, 0.7661815 , 0.22217968, 0.32509482]])
>>> a.__sizeof__()
312
>>> b.__sizeof__()
112
>>> a.dtype
dtype('float64')
>>> b.dtype
dtype('float64')
>>>

那么,为什么变量a的内存为312,变量b的内存为112?

1 个答案:

答案 0 :(得分:2)

  

为什么两个阵列的内存大小不同?

如果我们看一下base属性,差异是可以理解的:

>>> a.base
>>> b.base
array([[[ 0.17940875,  0.33674265,  0.14397669,  0.49947964,  0.70878022]],

       [[ 0.88072205,  0.69542991,  0.6094819 ,  0.47855311,  0.73319366]],

       [[ 0.75855104,  0.79885525,  0.77966685,  0.3756036 ,  0.81272082]],

       [[ 0.754227  ,  0.07242963,  0.16935453,  0.76840836,  0.10537832]],

       [[ 0.74316004,  0.76265098,  0.7661815 ,  0.22217968,  0.32509482]]])

另请参阅Internal memory layout of an ndarray

  

ndarray类的实例包含一个连续的   一维计算机内存段(由数组或数组拥有)   其他对象),并结合索引方案……

因此b.__sizeof__()只是ndarray的“簿记”信息,而实际的数组数据存储在b.base中。与此相反,a.base None a包含其内部的实际数据,而a.__sizeof__()是“簿记”和实际数据的总和。差异200正是我们对25个“ float64”数字的期望。

在每种情况下,实际数据大小都是由nbytes属性返回的。