我想从Python 3中的numpy数组中获取一个buffer。我找到了以下代码:
$ 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'
为什么我做错了?代码在Python2上运行良好,我使用的numpy版本是1.6.1。
发布于 2015-11-13 01:11:05
在返回bytes
对象方面,Numpy的arr.tobytes()
似乎比bytes(memoryview(arr))
快得多。因此,您可能还想看看tobytes()
。
在英特尔i7处理器、CPython v3.5.0、numpy v1.10.1上评测Windows7。
(编辑注意:在Ubuntu 16.04、英特尔i7 CPython、numpy v3.6.5、numpy v1.14.5上的结果顺序相同。)
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))
https://stackoverflow.com/questions/21821045
复制相似问题