In Python, you can query the memory usage of an array using various built-in modules such as numpy or the sys module. Here's an example using numpy:
import numpy as np# Allocate a numpy array of 10 integersmy_array = np.zeros(10, dtype=int)# Get the memory usage of the arraymem_usage = my_array.nbytes# Print the memory usage in bytesprint(mem_usage)# Print the memory usage in megabytesprint(mem_usage / (1024 ** 2)) |
In the above example, we create a numpy array of 10 integers using the numpy.zeros function. The nbytes attribute of the array returns the number of bytes used by the array. We then print the memory usage in bytes and megabytes.
Alternatively, you can use the sys module to get the memory usage of the array:
import numpy as npimport sys# Allocate a numpy array of 10 integersmy_array = np.zeros(10, dtype=int)# Get the size of the array in memorysize_in_bytes = sys.getsizeof(my_array)# Print the size in bytesprint(size_in_bytes)# Print the size in megabytesprint(size_in_bytes / (1024 ** 2)) |
In the above example, we create a numpy array of 10 integers and use the sys.getsizeof function to get the size of the array in memory. We then print the size in bytes and megabytes. Note that the sys.getsizeof function returns the size of the entire object in memory, which includes any additional memory overhead.