NumPy ndarray.nbytes
The ndarray.nbytes
attribute returns the total number of bytes consumed by the elements of a NumPy array.
It does not include memory used for metadata such as shape, dtype, or strides.
Syntax
ndarray.nbytes
Return Value
Type | Description |
---|---|
int | Returns the total number of bytes consumed by the elements of the array. |
Examples
1. Checking Memory Usage of an Integer Array
This example demonstrates how nbytes
calculates the total memory usage of an array.
import numpy as np
# Creating a NumPy array of integers
arr = np.array([1, 2, 3, 4, 5], dtype=np.int32)
# Getting total bytes consumed by the elements
bytes_used = arr.nbytes
print("Total bytes used by array elements:", bytes_used)
Output:
Total bytes used by array elements: 20
Since each integer (int32
) consumes 4 bytes and there are 5 elements, the total memory usage is 5 × 4 = 20
bytes.
2. Checking Memory Usage of a Float Array
Here, we check how much memory a float array consumes.
import numpy as np
# Creating a NumPy array of floats
arr = np.array([1.1, 2.2, 3.3, 4.4], dtype=np.float64)
# Getting total bytes consumed by the elements
bytes_used = arr.nbytes
print("Total bytes used by array elements:", bytes_used)
Output:
Total bytes used by array elements: 32
Since each float64
element occupies 8 bytes and there are 4 elements, the total memory usage is 4 × 8 = 32
bytes.
3. Memory Usage of a Multi-Dimensional Array
In this example, we examine the memory consumption of a 2D array.
import numpy as np
# Creating a 2D NumPy array of integers
arr = np.array([[10, 20, 30],
[40, 50, 60]], dtype=np.int16)
# Getting total bytes consumed by the elements
bytes_used = arr.nbytes
print("Total bytes used by array elements:", bytes_used)
Output:
Total bytes used by array elements: 12
Each int16
value takes 2 bytes. The array has 6 elements, so the total memory usage is 6 × 2 = 12
bytes.
4. Comparing Memory Usage of Different Data Types
This example shows how different data types impact memory consumption.
import numpy as np
# Creating NumPy arrays with different data types
arr_int8 = np.array([1, 2, 3, 4], dtype=np.int8)
arr_int64 = np.array([1, 2, 3, 4], dtype=np.int64)
arr_float32 = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32)
# Checking memory usage for each array
print("Bytes used by int8 array:", arr_int8.nbytes)
print("Bytes used by int64 array:", arr_int64.nbytes)
print("Bytes used by float32 array:", arr_float32.nbytes)
Output:
Bytes used by int8 array: 4
Bytes used by int64 array: 32
Bytes used by float32 array: 16
The memory usage differs because:
int8
uses 1 byte per element (4 × 1 = 4 bytes).int64
uses 8 bytes per element (4 × 8 = 32 bytes).float32
uses 4 bytes per element (4 × 4 = 16 bytes).