Wednesday, 10 August 2016

python - Why is if True slower than if 1?



Why is if True slower than if 1 in Python? Shouldn't if True be faster than if 1?



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:





  1. According to the response from Mr. Sylvain Defresne in this question, everything is implicitly converted to a bool first and then checked. So why is if True slower than if 1?

  2. Why is test3 slower than test1 even though only the return values are different?

  3. Like Question 2, but why is test4 a little faster than test2?



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.


Answer




True and False are not keywords in Python 2.



They must resolve at runtime. This has been changed in 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


Time error is in 1%, which is acceptable.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...