更新时间: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 long
s. 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.