numpy我正在尝试对整数(特别是对象)进行位移numpy.uint64,并且我需要它们很快。在下面的实现中,我将对象放入numpy.arrayonly 中,因为这是唯一可以接受位左移的对象。如果有更快的实施,我会接受。
from timeit import timeit
print(timeit("a << 1", "a = int(2**60)"))
print(timeit("a << 1", "import numpy as np; a = np.array([2 ** 60], dtype=np.uint64)"))
print(timeit("np.left_shift(a, 1)", "import numpy as np; a = np.array([2 ** 60], dtype=np.uint64)"))
Run Code Online (Sandbox Code Playgroud)
返回:
0.056681648000000084
1.208092987
1.1685176299999998
Run Code Online (Sandbox Code Playgroud)
为什么 python 比这个操作快得多numpy?有没有办法获得可比较的速度numpy?
关于性能差异,这似乎是合乎逻辑的:您正在一个元素上应用矢量化移位。到达移位部分并更改 numpy 结构会产生很大的开销。本机代码转换得更快。
好的,我在谷歌上搜索了当您尝试在一个元素上执行此操作时收到的错误消息,即:
>>> a = numpy.uint64(2**60)
>>> a << 3
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
TypeError: ufunc 'left_shift' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
Run Code Online (Sandbox Code Playgroud)
我发现了这个github问题:https ://github.com/numpy/numpy/issues/2524
这是因为移位数被转换为有符号类型,并且没有足够大的有符号整数类型来容纳 uint64。
现在一个好的解决方法(如github 问题评论中所示)是这样的:
a << numpy.uint64(1)
Run Code Online (Sandbox Code Playgroud)
(也许一劳永逸地构建“1”常量,并在所有代码中使用它来保存对象创建)
| 归档时间: |
|
| 查看次数: |
651 次 |
| 最近记录: |