简体   繁体   English

numpy ndarray 使用了多少内存?

[英]How much memory is used by a numpy ndarray?

Does anybody know how much memory is used by a numpy ndarray?有人知道 numpy ndarray 使用了多少内存吗? (with let's say 10,000,000 float elements). (假设有 10,000,000 个浮动元素)。

The array is simply stored in one consecutive block in memory.该数组只是存储在内存中的一个连续块中。 Assuming by "float" you mean standard double precision floating point numbers, then the array will need 8 bytes per element.假设“float”是指标准双精度浮点数,则数组每个元素将需要 8 个字节。

In general, you can simply query the nbytes attribute for the total memory requirement of an array, and itemsize for the size of a single element in bytes:通常,您可以简单地查询nbytes属性以获得数组的总内存需求,以及itemsize以字节为单位的单个元素的大小:

>>> a = numpy.arange(1000.0)
>>> a.nbytes
8000
>>> a.itemsize
8

In addtion to the actual array data, there will also be a small data structure containing the meta-information on the array.除了实际的数组数据外,还会有一个包含数组元信息的小数据结构。 Especially for large arrays, the size of this data structure is negligible.特别是对于大型数组,这种数据结构的大小可以忽略不计。

To get the total memory footprint of the NumPy array in bytes, including the metadata, you can use Python's sys.getsizeof() function:要以字节为单位获取 NumPy 数组的总内存占用量,包括元数据,您可以使用 Python 的sys.getsizeof()函数:

import sys
import numpy as np

a = np.arange(1000.0)

sys.getsizeof(a)

8104 bytes is the result 8104 字节是结果

sys.getsizeof() works for any Python object. sys.getsizeof()适用于任何 Python 对象。 It reports the internal memory allocation, not necessarily the memory footprint of the object once it is written out to some file format.它报告内部内存分配,不一定是对象写入某种文件格式后的内存占用。 Sometimes it is wildly misleading.有时它具有极大的误导性。 For example, with 2d arrays, it doesn't dig into the memory footprint of vector.例如,对于 2d 数组,它不会深入研究 vector 的内存占用。

See the docs here .请参阅此处的文档。 Ned Batcheldor shares caveats with using sys.getsizeof() here . Ned Batcheldor 在这里分享了使用sys.getsizeof()注意事项。

我高斯,很容易,我们可以通过print(a.size // 1024 // 1024, a.dtype)它类似于print(a.size // 1024 // 1024, a.dtype)有多少MB ,但是使用参数dtype , float=8B, int8=1B .. .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM