Why is Python 3 is considerably slower than Python 2? [duplicate] Why is Python 3 is considerably slower than Python 2? [duplicate] python-3.x python-3.x

Why is Python 3 is considerably slower than Python 2? [duplicate]


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.

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

I used sys.maxsize as sys.maxint was dropped from Python 3, but the integer value is basically the same.

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.

Since you cannot use the long type with xrange() on Python 2, I did not include a comparison for that function.