Reduce stacktrace of executing frame

2019-08-23 09:58发布

问题:

I'm doing my best to not be vague here and this all could be solved with a while loop, but as an exercise I've gone against the best practice of using a while loop in hopes to learn something new.

I'm re-learning some basics of CPU architecture, and thought it'd be a fun project to implement CPU emulation with "actual" JMP logic, or as close to it as possible in software.

However, I'm getting stuck on a rendering process of said logic. The code is (according to my best judgement) irrelevant to the problem but to avoid a back and fourth, the logic is as follows:

.LDA 0220
.ASL
.BCC FA

All this does it check a register, executes a bit shift to the left and jumps to memory address FA if a status flag is set correctly, if not it will jump back to .LDA and check the registers again.

The implementation in python does the same with a recursive function of each step in the code. Needless to say, this is beyond best practices but I thought it'd be a fun experiment in recursion and call-order.

If my math checks out, I end up with 16 280 recursive calls before python simply halts, and after 3 seconds or so just quits back out to the command prompt.

I've done sys.setrecursionlimit(self.dotcount*self.linecount) in a dirty attempt to increase the recursionlimit, and the goal here was to be able to execute 81 600 recursions (340x240 pixels, one recursive call per pixel rougly).

according to What is the maximum recursion depth in Python, and how to increase it? this is a bad idea, since the frames are pretty big, so my attempt to remedy this was:

for tb in inspect.stack():
    tb.frame.clear()

I've also tried (to no prevail) to use traceback.clear_frames(tb).
The dead end hits me with RuntimeError: cannot clear an executing frame.

My last resort/question is: Is it possible to reduce the executing frame to allow for more recursive calls that I know have a happy ending? I can't see that I'm even close to running out of RAM and the application isn't running even close to noticeably slow (I was expecting a slow down at some point).

If so, how do I free up the stack trace or increase the recursion depth further?

回答1:

So Python itself doesn't have a mechanism to do tail recursion directly. However, there are some interesting tail-recursion decorators which should help quite a bit. They work by editing the call stack before entering a recursive call again. Very clever!