Open In App

Find the memory size of a NumPy array

Improve
Improve
Like Article
Like
Save
Share
Report

In this post, we will see how to find the memory size of a NumPy array. So for finding the memory size of a NumPy array we are using following methods:

Using size and itemsize attributes of NumPy array

size: This attribute gives the number of elements present in the NumPy array.

itemsize: This attribute gives the memory size of one element of NumPy array in bytes.

Example 1:

Python3




# 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)


Output:

Size of the array:  3
Memory size of one array element in bytes:  4
Memory size of numpy array in bytes: 12

Example 2:

Python3




# 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)


Output:

Size of the array:  6
Length of one array element in bytes:  4
Memory size of numpy array in bytes: 24

Using nbytes attribute of NumPy array.

nbytes: This attribute gives the total bytes consumed by the elements of the NumPy array.

Example 1:

Python3




import numpy as n
from sys import getsizeof
 
l = [0] * 10
a = np.array(l)
 
print(getsizeof(l))
 
print(l.nbytes)


Output:

136
40

Example 2:

Python3




# 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)


Output:

Memory size of a NumPy array: 12

Example 3:

Python3




# 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)


Output:

Memory size of a NumPy array: 24


Last Updated : 13 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads