Python 无限整数

标签 python python-3.x memory integer long-integer

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/

相关文章:

python - numpy.where() 在这个例子中究竟是如何选择元素的?

python - 将行附加到空 DataFrame 不起作用

c# - 我要找回我的内存!我怎样才能真正处置一个控件?

c++ - 物理内存上的堆和栈在哪里?

python - 使用 win32com.client 计算 Excel 文件中的工作表数

python - 如何整理我的安装脚本,只保留使用过的内容?

python - 如果多个测试有特定异常,则停止 pytest 测试

python - pyqtdeploy : TypeError: expected str, 字节或 os.PathLike 对象,而不是 NoneType

python - 如何索引字典列表?

c# - 将 .jls 图像转换为字节 [] 数组时出现错误 : "Out of Memory ",