python - python中如何为numpy数组分配内存?

标签 python numpy memory mpi4py

我试图理解由 numpy“2D”数组引起的差异,即 numpy.zeros((3, )), numpy.zeros((3, 1)), numpy.zeros((1, 3) ).

我使用 id 查看每个元素的内存分配。但是我在 iPython 控制台中发现了一些奇怪的输出。

a = np.zeros((1, 3))
In [174]: id(a[0, 0])
Out[174]: 4491074656

In [175]: id(a[0, 1])
Out[175]: 4491074680

In [176]: id(a[0, 2])
Out[176]: 4491074704

In [177]: id(a[0, 0])
Out[177]: 4491074728

In [178]: id(a[0, 1])
Out[178]: 4491074800

In [179]: id(a)
Out[179]: 4492226688

In [180]: id(a[0, 1])
Out[180]: 4491074752

元素的内存是

  1. 不连续
  2. 改变而不重新分配

而且形状为(1, 3)的数组中的元素一开始看起来是连续内存的,但其他形状就不是这样了,比如

In [186]: a = np.zeros((3, ))

In [187]: id(a)
Out[187]: 4490927280

In [188]: id(a[0])
Out[188]: 4491075040

In [189]: id(a[1])
Out[189]: 4491074968
In [191]: a = np.random.rand(4, 1)

In [192]: id(a)
Out[192]: 4491777648

In [193]: id(a[0])
Out[193]: 4491413504

In [194]: id(a[1])
Out[194]: 4479900048

In [195]: id(a[2])
Out[195]: 4491648416

其实我不太确定 id 是否适合在 Python 中检查内存。据我所知,我想在 Python 中没有简单的方法来获取变量的物理地址。

就像C或Java一样,我希望这种“二维”数组中的元素在内存中应该是连续的,这似乎不是真的。此外,id的结果一直在变化,这让我很困惑。

我对此很感兴趣,因为我正在使用 mpi4py 一点点,我想弄清楚变量是如何在 CPU 之间发送/接收的。

最佳答案

Numpy 数组将其数据保存在与对象本身分离的内存区域中。如下图所示:

enter image description here

要获取数据的地址,您需要创建数组 View 并检查 ctypes.data 属性 是第一个数据元素的地址:

import numpy as np
a = np.zeros((3, 2))
print(a.ctypes.data)
print(a[0:1, 0].ctypes.data)
print(a[0:1, 1].ctypes.data)
print(a[1:2, 0].ctypes.data)
print(a[1:2, 1].ctypes.data)

关于python - python中如何为numpy数组分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57262885/

相关文章:

python - 使用线程时访问父类(super class)变量

python - 如何向窗口添加第二个弹跳球?

python - 如何在 numpy 中创建子矩阵

python - 基于另一种阵列形状的零焊盘阵列

android - 启动 android 通知设置 Activity 导致泄漏的 Intent 接收器

c - 只读存储器是如何在 C 中实现的?

python - (PYTHON) 用字典更新列表中的变量

c# - 从 C# .net 调用 python.py

python - 如何在 numpy 中向量化这个循环差异?

c++ - 在 msvc Debug模式下,堆栈中有 cdcdcdcd 是否正常