Python 无限整数

Python Infinite Integers

Python3个整数有unlimited precision。实际上,这是受计算机内存的限制。

考虑以下代码:

i = 12345
while True:
    i = i * 123

这显然会失败。但这会是什么结果呢?整个RAM(和页面文件)都被这一个整数填满了(除了被其他进程占用的space)?

或者是否有一种保护措施可以在它发展到这一步之前将其捕获?

您可以检查发生了什么,而不必冒填满所有可用内存的风险。你可以 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.