python - Why is if True slower than if 1? -
why if true slower if 1 in python? shouldn't if true faster if 1?
i trying learn timeit module. starting basics, 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 confused these things:
- according response mr. sylvain defresne in this question, implicitly converted
boolfirst , checked. whyif trueslowerif 1? - why
test3slowertest1thoughreturnvalues different? - like question 2, why
test4little fastertest2?
note: ran timeit 3 times , took average of results, posted times here along code.
this question not relate how micro benchmarking(which did in example understand basic) why checking 'true' variable slower constant.
true , false not keywords in python 2.
they must resolve @ runtime. 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 in 1%, acceptable.
Comments
Post a Comment