NumPy: Get the memory usage by NumPy arrays
Calculate Memory Usage of Array
Write a NumPy program to get NumPy array memory usage.
Sample Solution:
Python Code:
# Importing the NumPy library and aliasing it as 'np'
import numpy as np
# Importing the getsizeof function from sys module
from sys import getsizeof
# Creating a list 'x' containing 1024 zeros
x = [0] * 1024
# Creating a NumPy array 'y' from the list 'x'
y = np.array(x)
# Printing the size of the list 'x' using the getsizeof() function from the sys module
print(getsizeof(x))
Sample Output:
8248
Explanation:
In the above code –
x = [0] * 1024: Create a Python list 'x' with 1024 elements, each element being 0.
y = np.array(x): Convert the Python list 'x' into a NumPy array 'y'.
getsizeof(x): Use the getsizeof() function from the sys module to get the memory size of the Python list 'x' in bytes.
Finally print() function prints the memory size of the Python list 'x' in bytes.
For more Practice: Solve these Related Problems:
- Write a NumPy program to calculate the total memory usage of an array using its nbytes attribute.
- Create a function that reports the memory footprint of an array in bytes, kilobytes, and megabytes.
- Test the memory usage calculation on arrays of different dtypes and sizes to compare results.
- Implement a solution that sums the memory usage of multiple arrays to get an overall footprint.
Python-Numpy Code Editor:
Previous: Write a NumPy program to create a Cartesian product of two arrays into single array of 2D points.Next: Write a NumPy program to build an array of all combinations of three NumPy arrays.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.