Is there a reason Python 3 enumerates slower than Python 2?

前端 未结 2 737
天涯浪人
天涯浪人 2020-12-02 23:20

Python 3 appears to be slower in enumerations for a minimum loop than Python 2 by a significant margin, which appears to be getting worse with newer versions of Python 3.

2条回答
  •  情歌与酒
    2020-12-02 23:46

    The difference is due to the replacement of the int type with the long type. Obviously operations with long integers are going to be slower because the long operations are more complex.

    If you force python2 to use longs by setting cnt to 0L the difference goes away:

    $python2 -mtimeit -n5 -r2 -s"cnt=0L" "for i in range(10000000): cnt += 1L"
    5 loops, best of 2: 1.1 sec per loop
    $python3 -mtimeit -n5 -r2 -s"cnt=0" "for i in range(10000000): cnt += 1"
    5 loops, best of 2: 686 msec per loop
    $python2 -mtimeit -n5 -r2 -s"cnt=0L" "for i in xrange(10000000): cnt += 1L"
    5 loops, best of 2: 714 msec per loop
    

    As you can see on my machine python3.4 is faster than both python2 using range and using xrange when using longs. The last benchmark with python's 2 xrange shows that the difference in this case is minimal.

    I don't have python3.3 installed, so I cannot make a comparison between 3.3 and 3.4, but as far as I know nothing significant changed between these two versions (regarding range), so the timings should be about the same. If you see a significant difference try to inspect the generated bytecode using the dis module. There was a change about memory allocators (PEP 445) but I have no idea whether the default memory allocators were modified and which consequences there were performance-wise.

提交回复
热议问题