So I was messing around in idle with recursion, and I noticed that a loop using recursion was much slower then a regular while loop, and I was wondering if anyone knew why. I have included the tests that I had done below:
>>> import timeit
>>> setu="""def test(x):
x=x-1
if x==0:
return x
else:
test(x)
"""
>>> setu2="""
x=10
while x>0:
x=x-1
"""
>>> timeit.timeit(stmt="test(10)",setup=setu,number=100)
0.0006629826315997432
>>> timeit.timeit(stmt=setu2,number=100)
0.0002488750590750044
>>> setu="""def test(x):
x=x-1
if x==0:
return x
test(x)
"""
>>> timeit.timeit(stmt="test(10)",setup=setu,number=100)
0.0006419437090698921
During the last test however, I noticed that if I took out the else
statement, it showed a slight improvement in speed, so I am wondering if the if statement is the cause of this loop speed difference?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…