Linux、Mac和Windows的硬递归限制是多少?

2024-05-16 05:24:46 发布

您现在位置:Python中文网/ 问答频道 /正文

Python的sys模块provides a functionsetrecursionlimit允许您更改Python的最大递归限制。医生说:

The highest possible limit is platform-dependent.

我的问题是:在CPython下,各种平台的最大可能限制是什么?我想知道Linux、Mac和Windows的值。

更新:我们能不能避免回答“你做错了”?我知道尝试进行非常深的递归通常是个坏主意。我已经考虑了我的具体情况的利弊,并决定我要做这件事。


Tags: 模块theislinuxsys平台cpythonprovides
2条回答

至少在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()

我还没试过看threading.stack_size上有什么限制,但请随意尝试。。。那是你需要找的地方。

总之,sys.setrecursionlimit只是解释器本身强制的一个限制。threading.stack_size允许您操作操作系统施加的实际限制。如果先达到后一个限制,Python将完全崩溃。

在CPython中不应该过度使用递归调用。它没有尾部优化,函数调用占用大量内存和处理时间。这些限制可能不适用于其他实现,它不在蓝图中。

在CPython中,递归对于遍历数据结构(对于每个人来说,1000的限制应该足够)来说是很好的,但对于算法来说则不行。如果我要实现,比如说,与图形相关的算法,并达到递归限制,我要么实现自己的堆栈并使用迭代,要么查找在用手提高极限之前在C/C++ ++中实现的库。

相关问题 更多 >