本文介绍了为什么删除 else 会减慢我的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下功能:
def fact1(n):如果 n
它们应该是等价的.但存在性能差异:
>>>T(lambda : fact1(1)).repeat(number=10000000)[2.5754408836364746, 2.5710129737854004, 2.5678811073303223]>>>T(lambda : fact2(1)).repeat(number=10000000)[2.8432059288024902, 2.834425926208496, 2.8364310264587402]没有 else
的版本慢 10%.这是相当重要的.为什么?
解决方案
对我来说,它们的速度几乎相同:(Debian 上的 Python 2.6.6)
在 [4]: %timeit fact1(1)10000000 个循环,最好的 3 个:每个循环 151 ns在 [5] 中:%timeit fact2(1)10000000 个循环,最好的 3 个:每个循环 154 ns
字节码也很相似:
在[6]中:dis.dis(fact1)2 0 LOAD_FAST 0 (n)3 LOAD_CONST 1 (2)6 COMPARE_OP 0 (<)9 JUMP_IF_FALSE 5(到 17)12 POP_TOP3 13 LOAD_CONST 2 (1)16 RETURN_VALUE>>17 POP_TOP5 18 LOAD_FAST 0 (n)21 LOAD_GLOBAL 0(事实)24 LOAD_FAST 0 (n)27 LOAD_CONST 2 (1)30 BINARY_SUBTRACT31 CALL_FUNCTION 134 BINARY_MULTIPLY35 RETURN_VALUE36 LOAD_CONST 0 (无)39 RETURN_VALUE在 [7] 中:dis.dis(fact2)2 0 LOAD_FAST 0 (n)3 LOAD_CONST 1 (2)6 COMPARE_OP 0 (
唯一的区别是带有 else
的版本包括返回 None
的代码,以防控制到达函数体的末尾.
Consider the following functions:
def fact1(n):
if n < 2:
return 1
else:
return n * fact1(n-1)
def fact2(n):
if n < 2:
return 1
return n * fact2(n-1)
They should be equivalent. But there's a performance difference:
>>> T(lambda : fact1(1)).repeat(number=10000000)
[2.5754408836364746, 2.5710129737854004, 2.5678811073303223]
>>> T(lambda : fact2(1)).repeat(number=10000000)
[2.8432059288024902, 2.834425926208496, 2.8364310264587402]
The version without the else
is 10% slower. This is pretty significant. Why?
解决方案
For me, they are virtually the same speed: (Python 2.6.6 on Debian)
In [4]: %timeit fact1(1)
10000000 loops, best of 3: 151 ns per loop
In [5]: %timeit fact2(1)
10000000 loops, best of 3: 154 ns per loop
The byte code is also very similar:
In [6]: dis.dis(fact1)
2 0 LOAD_FAST 0 (n)
3 LOAD_CONST 1 (2)
6 COMPARE_OP 0 (<)
9 JUMP_IF_FALSE 5 (to 17)
12 POP_TOP
3 13 LOAD_CONST 2 (1)
16 RETURN_VALUE
>> 17 POP_TOP
5 18 LOAD_FAST 0 (n)
21 LOAD_GLOBAL 0 (fact)
24 LOAD_FAST 0 (n)
27 LOAD_CONST 2 (1)
30 BINARY_SUBTRACT
31 CALL_FUNCTION 1
34 BINARY_MULTIPLY
35 RETURN_VALUE
36 LOAD_CONST 0 (None)
39 RETURN_VALUE
In [7]: dis.dis(fact2)
2 0 LOAD_FAST 0 (n)
3 LOAD_CONST 1 (2)
6 COMPARE_OP 0 (<)
9 JUMP_IF_FALSE 5 (to 17)
12 POP_TOP
3 13 LOAD_CONST 2 (1)
16 RETURN_VALUE
>> 17 POP_TOP
4 18 LOAD_FAST 0 (n)
21 LOAD_GLOBAL 0 (fact)
24 LOAD_FAST 0 (n)
27 LOAD_CONST 2 (1)
30 BINARY_SUBTRACT
31 CALL_FUNCTION 1
34 BINARY_MULTIPLY
35 RETURN_VALUE
The only difference is that the version with the else
includes code to return None
in case control reaches the end of the function body.
这篇关于为什么删除 else 会减慢我的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!