且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python 3枚举比Python 2慢是有原因的吗?

更新时间:2021-09-22 22:23:01

差异是由于将int类型替换为long类型.显然,由于long操作更复杂,因此使用长整数的操作将变得更慢.

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.

如果通过将cnt设置为0L来强制python2使用long,则差异消失:

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

正如您在我的机器上看到的那样,使用range时,使用range和使用xrange的python3.4都比python2更快. python 2 xrange的最后一个基准测试表明,这种情况下的差异很小.

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.

我没有安装python3.3,因此无法在3.3和3.4之间进行比较,但是据我所知,这两个版本之间均无重大变化(关于range),因此计时应为相同.如果您发现明显的差异,请尝试使用 dis 检查生成的字节码.模块.关于内存分配器的更改( PEP 445 ),但我不知道是否修改了默认的内存分配器,以及在性能方面有哪些后果.

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.