Python无限整数

mcu*_*mcu 5 python memory integer python-3.x long-integer

Python 3整数具有无限精度.在实践中,这受到计算机内存的限制.

考虑以下代码:

i = 12345
while True:
    i = i * 123
Run Code Online (Sandbox Code Playgroud)

这显然会失败.但结果会是什么呢?整个RAM(和页面文件)填充了这个整数(除了其他进程占用的空间)?

或者在它到达那么远之前是否有保护措施?

jfs*_*jfs 1

您可以检查发生了什么,而不必冒填满所有可用内存的风险。您可以明确设置内存限制

#!/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
Run Code Online (Sandbox Code Playgroud)

此代码消耗 100% CPU(在单核上),并且消耗的内存增长非常非常缓慢。

原则上,您应该MemoryError在计算机化为灰烬之前的某个时刻了解这种情况是否发生。CPython 使用连续的内存块来存储数字,因此即使有可用但碎片化的 RAM,您也可能会收到错误。

您的特定代码不应该触发它,但一般来说,OverflowError如果您尝试构造一个大于sys.maxsizebytes的整数,您也可以得到它。