所以我在递归闲置中搞砸了,我注意到使用递归的循环比常规的 while 循环慢得多,我想知道是否有人知道为什么。我已经包括了我在下面所做的测试:
>>> 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
然而,在最后一次测试中,我注意到如果我取出else
语句,它显示速度略有提高,所以我想知道 if 语句是否是导致这种循环速度差异的原因?