Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么对于左位移位,`numpy`比python慢?_Python_Numpy - Fatal编程技术网

为什么对于左位移位,`numpy`比python慢?

为什么对于左位移位,`numpy`比python慢?,python,numpy,Python,Numpy,我正在尝试对numpy整数进行位移位,特别是numpy.uint64对象,我需要它们速度快。在下面的实现中,我将对象放在numpy.array中,因为它是唯一可以接受位左移位的对象。如果有任何更快的实施,我将接受它 from timeit import timeit print(timeit("a << 1", "a = int(2**60)")) print(timeit("a << 1", "import numpy as np; a = np.array([2 **

我正在尝试对numpy整数进行位移位,特别是numpy.uint64对象,我需要它们速度快。在下面的实现中,我将对象放在numpy.array中,因为它是唯一可以接受位左移位的对象。如果有任何更快的实施,我将接受它

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)"))

为什么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''
我发现了这个github问题:

这是因为移位数转换为有符号类型,并且没有大到足以容纳uint64的有符号整数类型

如图所示,一个很好的解决方法是:


可能一次性构建1常量,并在所有代码中使用它来保存对象创建

您正在对一个元素应用矢量化移位。只需到达移位部分并更改numpy结构,就会有很大的开销。本机代码移动得更快。但是,如果你做10000个轮班,这将改变你如何建议加快它?a听起来有一个限制:如果Numba是你的选择,你也可以尝试类似的东西。用这个注释更新你的答案,我会给你一个绿色的复选标记:这个答案在速度上是可比的-我正在写这个答案。标量/数组移位的情况有效,因为标量在混合标量/数组操作中可能会降级为较小的类型,如果需要,使用一些特殊处理来选择无符号类型。看,肯定会有混淆的风险,我更喜欢使类型显式化,而不是依赖它。
>>> 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''
a << numpy.uint64(1)