Python numpy.getbuffer导致AttributeError:&x27;模块';对象没有属性';getbuffer';
我想从Python3中的numpy数组中获取一个缓冲区。 我发现了以下代码:Python numpy.getbuffer导致AttributeError:&x27;模块';对象没有属性';getbuffer';,python,python-3.x,numpy,Python,Python 3.x,Numpy,我想从Python3中的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) &
$ 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)
但是,它会在最后一步产生错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'getbuffer'
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AttributeError:“模块”对象没有属性“getbuffer”
为什么我做错了?
该代码适用于Python2。
我使用的numpy版本是1.6.1。根据:
PyBuffer(对象)
由于Py3中有一个本机缓冲区对象,memoryview
,因此
newbuffer
和getbuffer
函数从Py3中的多数组中删除:
它们的功能由新的memoryview对象接管
导入numpy
>>>a=努比·阿兰奇(10)
>>>记忆视图(a)
>>>m=_
>>>m[0]=9
>>>a
数组([9,1,2,3,4,5,6,7,8,9])
Numpy似乎比返回字节
对象要快得多。
因此,您可能还想看看tobytes()
在英特尔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上的结果顺序相同。)
结果
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))
setup = '''import numpy as np; x = np.random.random(n).reshape(n//10, -1)'''
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))