查找一个NumPy数组的内存大小
在这篇文章中,我们将看到如何找到NumPy数组的内存大小。因此,为了找到NumPy数组的内存大小,我们使用以下方法。
使用NumPy数组的size和itemsize属性
size:该属性给出了NumPy数组中存在的元素数量。
itemsize:该属性给出了NumPy数组中一个元素的内存大小,单位为字节。
示例 1:
# import library
import numpy as np
# create a numpy 1d-array
x = np.array([100,20,34])
print("Size of the array: ",
x.size)
print("Memory size of one array element in bytes: ",
x.itemsize)
# memory size of numpy array in bytes
print("Memory size of numpy array in bytes:",
x.size * x.itemsize)
输出:
Size of the array: 3
Memory size of one array element in bytes: 4
Memory size of numpy array in bytes: 12
示例 2:
# import library
import numpy as np
# create a numpy 2d-array
x = np.array([[100, 20, 34],
[300, 400, 600]])
print("Size of the array: ",
x.size)
print("Memory size of one array element in bytes: ",
x.itemsize)
# memory size of numpy array
print("Memory size of numpy array in bytes:",
x.size * x.itemsize)
输出:
Size of the array: 6
Length of one array element in bytes: 4
Memory size of numpy array in bytes: 24
使用NumPy数组的nbytes属性
nbytes:该属性给出了NumPy数组的元素所消耗的总字节数。
示例 1:
import numpy as n
from sys import getsizeof
l = [0] * 10
a = np.array(l)
print(getsizeof(l))
print(l.nbytes)
输出:
136
40
示例 2:
# import library
import numpy as np
# create numpy 1d-array
x = np.array([100, 20, 34])
print("Memory size of a NumPy array:",
x.nbytes)
输出:
Memory size of a NumPy array: 12
示例 3:
# import library
import numpy as np
# create numpy 2d-array
x = np.array([[100, 20, 34],
[300, 400, 600]])
print("Memory size of a NumPy array:",
x.nbytes)
输出:
Memory size of a NumPy array: 24