numpy.getbuffer导致AttributeError:'module'对象没有属性'getbuffer'

Evg*_*lai 9 python numpy python-3.x

我想从Python 3中的numpy数组中获取缓冲区.我找到了以下代码:

$ python3
Python 3.2.3 (default, Sep 25 2013, 18:25:56) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> a = numpy.arange(10)
>>> numpy.getbuffer(a)
Run Code Online (Sandbox Code Playgroud)

但是它会在最后一步产生错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'getbuffer'
Run Code Online (Sandbox Code Playgroud)

我为什么做错了?该代码适用于Python 2.我使用的numpy版本是1.6.1.

fal*_*tru 8

根据开发人员关于过渡到Python 3的说明:

PyBuffer(对象)

由于Py3中有一个本机缓冲区对象,因此在Py3 中从多个阵列中删除memoryviewnewbuffer和它们的函数:它们的功能由新的memoryview对象接管.getbuffer

>>> import numpy
>>> a = numpy.arange(10)
>>> memoryview(a)
<memory at 0xb60ae094>
>>> m = _
>>> m[0] = 9
>>> a
array([9, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Run Code Online (Sandbox Code Playgroud)


mab*_*mab 6

Numpy的arr.tobytes()速度似乎比bytes(memoryview(arr))返回bytes对象快得多。因此,您可能还想看看tobytes()

在Intel i7 CPU,CPython v3.5.0,numpy v1.10.1上对Windows 7进行性能分析

编辑注:在Ubuntu 16.04,Intel i7 CPU,CPython v3.6.5,numpy v1.14.5上相同的结果顺序。)

setup = '''import numpy as np; x = np.random.random(n).reshape(n//10, -1)'''
Run Code Online (Sandbox Code Playgroud)

结果

globals: {'n': 100}, tested 1e+06 times

   time (s) speedup                  methods
0  0.163005   6.03x              x.tobytes()
1  0.491887   2.00x         x.data.tobytes()
2  0.598286   1.64x  memoryview(x).tobytes()
3  0.964653   1.02x            bytes(x.data)
4  0.982743             bytes(memoryview(x))


globals: {'n': 1000}, tested 1e+06 times

   time (s) speedup                  methods
0  0.378260   3.21x              x.tobytes()
1  0.708204   1.71x         x.data.tobytes()
2  0.827941   1.47x  memoryview(x).tobytes()
3  1.189048   1.02x            bytes(x.data)
4  1.213423             bytes(memoryview(x))


globals: {'n': 10000}, tested 1e+06 times

   time (s) speedup                  methods
0  3.393949   1.34x              x.tobytes()
1  3.739483   1.22x         x.data.tobytes()
2  4.033783   1.13x  memoryview(x).tobytes()
3  4.469730   1.02x            bytes(x.data)
4  4.543620             bytes(memoryview(x))
Run Code Online (Sandbox Code Playgroud)