更新时间:2021-08-23 03:06:32
不同之处在于 int
类型的实现。 Python 3.x仅使用任意大小的整数类型(在2.x中为 long
),而在Python 2.x中,其值最高为 sys .maxint
使用更简单的 int
类型,该类型在引擎盖下使用简单的C long
The difference is in the implementation of the int
type. Python 3.x uses the arbitrary-sized integer type (long
in 2.x) exclusively, while in Python 2.x for values up to sys.maxint
a simpler int
type is used that uses a simple C long
under the hood.
一旦将循环限制为 long
个整数,Python 3.x是更快:
Once you limit your loops to long
integers, Python 3.x is faster:
>>> from timeit import timeit
>>> MAX_NUM = 3*10**3
>>> def bar():
... i = MAX_NUM + sys.maxsize
... while i > sys.maxsize:
... i -= 1
...
Python 2:
>>> timeit(bar, number=10000)
5.704327821731567
Python 3:
>>> timeit(bar, number=10000)
3.7299320790334605
我用过 sys.maxsize
作为 sys.maxint
从Python 3中删除的,但整数值基本相同。
I used sys.maxsize
as sys.maxint
was dropped from Python 3, but the integer value is basically the same.
因此,Python 2的速度差异仅限于第一个(2 ** 63)-64位为1个整数,(2 ** 31)-32位系统为1个整数。
The speed difference in Python 2 is thus limited to the first (2 ** 63) - 1 integers on 64-bit, (2 ** 31) - 1 integers on 32 bit systems.
由于不能在 xrange()
上使用 long
类型Python 2,我没有对该函数进行比较。
Since you cannot use the long
type with xrange()
on Python 2, I did not include a comparison for that function.