0
0
NumPydata~5 mins

Monitoring memory usage in NumPy

Choose your learning style9 modes available
Introduction

Monitoring memory usage helps you see how much computer memory your numpy arrays use. This keeps your programs fast and avoids crashes.

You want to check how much memory a numpy array takes before running big calculations.
You need to optimize your program to use less memory.
You want to compare memory use of different numpy arrays.
You are debugging a program that runs out of memory.
You want to learn how numpy stores data in memory.
Syntax
NumPy
array.nbytes

nbytes is a property of numpy arrays that shows total bytes used by the array data.

This does not count Python object overhead, only the raw data size.

Examples
Shows memory in bytes for a small integer array.
NumPy
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr.nbytes)
Shows memory used by a 100x100 array of zeros.
NumPy
arr = np.zeros((100, 100))
print(arr.nbytes)
Shows memory for 10 double precision floats.
NumPy
arr = np.ones(10, dtype=np.float64)
print(arr.nbytes)
Sample Program

This program creates a small 3x3 numpy array and prints how many bytes it uses in memory.

NumPy
import numpy as np

# Create a 3x3 array of integers
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Print the memory usage in bytes
print(arr.nbytes)
OutputSuccess
Important Notes

Memory size depends on the data type. For example, int64 uses 8 bytes per element.

Use arr.itemsize to see bytes per element.

Large arrays can use a lot of memory, so check nbytes to avoid crashes.

Summary

nbytes shows total memory used by numpy array data.

It helps you understand and control memory use in your programs.

Always check memory when working with big arrays.