Fog*_*ird 33
在Windows上(至少),sys.setrecursionlimit不是完整的故事.硬限制是基于每个线程的,您需要在threading.stack_size达到特定限制时调用并创建新线程.(我认为1MB,但不确定)我已经使用这种方法将其增加到64MB堆栈.
import sys
import threading
threading.stack_size(67108864) # 64MB stack
sys.setrecursionlimit(2 ** 20) # something real big
# you actually hit the 64MB limit first
# going by other answers, could just use 2**32-1
# only new threads get the redefined stack size
thread = threading.Thread(target=main)
thread.start()
Run Code Online (Sandbox Code Playgroud)
我没有试图看到可能存在的限制threading.stack_size,但可以随意尝试......这就是你需要看的地方.
总之,sys.setrecursionlimit这只是解释器本身强制执行的限制. threading.stack_size让您操纵操作系统施加的实际限制.如果你首先达到后一个限制,Python将完全崩溃.
您不应该在 CPython 中过度使用递归调用。它没有尾部优化,函数调用使用大量内存和处理时间。这些限制可能不适用于其他实现,它不在蓝图中。
在 CPython 中,递归适用于遍历数据结构(其中 1000 的限制对每个人来说都足够了),但不适用于算法。例如,如果我要实现与图形相关的算法并达到递归限制,我要么实现自己的堆栈并使用迭代,要么在手动提高限制之前寻找用 C/C++/其他语言实现的库。
| 归档时间: |
|
| 查看次数: |
9698 次 |
| 最近记录: |