Python 3 整数有 unlimited precision .实际上,这受到计算机内存的限制。
考虑以下代码:
i = 12345
while True:
i = i * 123
这显然会失败。但这会是什么结果呢?整个RAM(和页面文件)都被这一个整数填满了(其他进程占用的空间除外)?
或者是否有一种保护措施可以在它发展到这一步之前将其捕获?
最佳答案
您可以检查发生了什么,而不必冒填满所有可用内存的风险。你可以 set the memory limit explicitly :
#!/usr/bin/env python
import contextlib
import resource
@contextlib.contextmanager
def limit(limit, type=resource.RLIMIT_AS):
soft_limit, hard_limit = resource.getrlimit(type)
resource.setrlimit(type, (limit, hard_limit)) # set soft limit
try:
yield
finally:
resource.setrlimit(type, (soft_limit, hard_limit)) # restore
with limit(100 * (1 << 20)): # 100MiB
# do the thing that might try to consume all memory
i = 1
while True:
i <<= 1
此代码消耗 100% 的 CPU(在单核上)并且消耗的内存增长非常非常缓慢。
原则上,您应该在某个时间点得到 MemoryError
,它是否发生在您的计算机变成灰尘之前尚不清楚。 CPython uses a continuous block of memory to store the digits因此,即使有可用但碎片化的 RAM,您也可能会收到错误消息。
您的特定代码不应触发它,但通常您也可以获得 OverflowError
if you try to construct an integer larger than sys.maxsize
bytes .
关于Python 无限整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32684126/