Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

recursion - Why is recursive function execution time faster on average with more iterations in python?

I'm comparing the speed of two different functions in python. They are two implementations of some generic algorithm, where one is recursive, and the other uses a stack.

When using time and timeit to view the speed of the one single iteration, the recursive implementation is about 40x slower. This is to be expected as recursion is relatively slow.

However, when I run 1000000 iterations using both time and timeit, the time taken to complete all those iterations for the recursive implementation is only 30% slower than the stack implementation.

This makes no sense to me at all. The reason I used time was to check whether timeit wasn functioning properly when timing the recursive function, because I thought there must have been some error.

It's important to note that I made sure that the same number of iterations were used when timing each function. I also ran these timings multiple times, and I still got the same conclusion.

Are there any potential reasons as to why more iterations on timeit resulted in this recursion algorithm to actually be so close in speed compared to the non-recursive version?

Unfortunately I cannot show the implementation code. I don't need a definitive answer, I just wanted potential ideas as to why this was. However, it was your basic

iterationNum=100000
print(timeit.timeit(recursiveImplementation, number=iterationNum))
print(timeit.timeit(stackImplementation, number=iterationNum))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you see a large difference between testing 1 iteration and 1000 iterations, it is likely that the recursive function uses some form of memoization held in a global variable that makes subsequent calls faster. Keep in mind that a mutable default parameter could end up with a global scope as well. In any case, there are surely side effects from the recursive implementation that impact subsequent calls


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...