为什么如果真比,如果1慢? [英] Why is if True slower than if 1?
问题描述
为什么如果真
比慢,如果1
在Python?不应该如果真
比更快,如果1
?
Why is if True
slower than if 1
in Python? Shouldn't if True
be faster than if 1
?
我是想学习 timeit
模块。从最基本的开始,我想这些:
I was trying to learn the timeit
module. Starting with the basics, I tried these:
>>> def test1():
... if True:
... return 1
... else:
... return 0
>>> print timeit("test1()", setup = "from __main__ import test1")
0.193144083023
>>> def test2():
... if 1:
... return 1
... else:
... return 0
>>> print timeit("test2()", setup = "from __main__ import test2")
0.162086009979
>>> def test3():
... if True:
... return True
... else:
... return False
>>> print timeit("test3()", setup = "from __main__ import test3")
0.214574098587
>>> def test4():
... if 1:
... return True
... else:
... return False
>>> print timeit("test4()", setup = "from __main__ import test4")
0.160849094391
我对这些事情感到困惑:
I am confused by these things:
- 据西尔Defresne先生在回应<一个href=\"http://stackoverflow.com/questions/100732/why-is-if-not-someobj-better-than-if-someobj-none-in-python\">this问题,一切都隐式转换为
布尔
,然后再检查。那么,为什么是如果真
比慢,如果1
? - 为什么
TEST3
比测试1
即使只有收益$ C慢$ C>值是不同的?
- 就像第二个问题,但为什么是
TEST4
一点点的更快的比测试2
?
- According to the response from Mr. Sylvain Defresne in this question, everything is implicitly converted to a
bool
first and then checked. So why isif True
slower thanif 1
? - Why is
test3
slower thantest1
even though only thereturn
values are different? - Like Question 2, but why is
test4
a little faster thantest2
?
请注意:我跑了 timeit
三次,拿着结果的平均值,然后贴在这里的时间与code沿
NOTE: I ran timeit
three times and took the average of the results, then posted the times here along with the code.
这个问题并不涉及到如何做微基准测试(我没有在这个例子中,但我也明白,这是太简单了),但为什么检查真变量大于一个常数慢。
This question does not relate to how to do micro benchmarking(which I did in this example but I also understand that it is too basic) but why checking a 'True' variable is slower than a constant.
推荐答案
真
和假
不是关键字的Python 2 。
他们必须在运行时解决。这在 Python中被改变3
They must resolve at runtime. This has been changed in Python 3
在Python 3的相同的测试:
Same test on Python 3:
>>> timeit.timeit('test1()',setup="from __main__ import test1", number=10000000)
2.806439919999889
>>> timeit.timeit('test2()',setup="from __main__ import test2", number=10000000)
2.801301520000038
>>> timeit.timeit('test3()',setup="from __main__ import test3", number=10000000)
2.7952816800000164
>>> timeit.timeit('test4()',setup="from __main__ import test4", number=10000000)
2.7862537199999906
时间误差是1%,这是可以接受的。
Time error is in 1%, which is acceptable.
这篇关于为什么如果真比,如果1慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!