为什么按位运算符要比乘法/除法/模运算慢? [英] Why are bitwise operators slower than multiplication/division/modulo?
问题描述
众所周知,乘法,整数除法和以2的幂进行模运算可以更有效地重写为按位运算:
It's a well known fact that multiplication, integer division, and modulo by powers of two can be rewritten more efficiently as bitwise operations:
>>> x = randint(50000, 100000)
>>> x << 2 == x * 4
True
>>> x >> 2 == x // 4
True
>>> x & 3 == x % 4
True
在C/C ++和Java等编译语言中,测试表明,按位运算通常比算术运算更快. (请参见此处和
In compiled languages such as C/C++ and Java, tests have shown that bitwise operations are generally faster than arithmetic operations. (See here and here). However, when I test these in Python, I am getting contrary results:
In [1]: from random import randint
...: nums = [randint(0, 1000000) for _ in range(100000)]
In [2]: %timeit [i * 8 for i in nums]
7.73 ms ± 397 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [3]: %timeit [i << 3 for i in nums]
8.22 ms ± 368 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [4]: %timeit [i // 8 for i in nums]
7.05 ms ± 393 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [5]: %timeit [i >> 3 for i in nums]
7.55 ms ± 367 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [6]: %timeit [i % 8 for i in nums]
5.96 ms ± 503 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [7]: %timeit [i & 7 for i in nums]
8.29 ms ± 816 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
如您所见,按位运算比其算术运算要慢,尤其是对于模运算.我对另一组数字重复了此测试,并得到了相同的结果.是否有一个原因?如果重要的话,这些测试是在CPython 3.6.7中进行的.
As you can see, bitwise operations are slower than their arithmetic counterparts, especially for modulo. I repeated this test for another set of numbers, and got the same result. Is there a reason for this? These tests were in CPython 3.6.7, if that matters.
推荐答案
*
, %
和 /
全部都有用于单边"整数的快速路径. <<
, &
不要.他们正在通过通用的任意精度代码路径.
*
, %
, and /
all have fast paths for single-"limb" integers. <<
, >>
, and &
don't. They're going through the general-purpose arbitrary-precision code path.
这篇关于为什么按位运算符要比乘法/除法/模运算慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!