You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python循环内存持续累积导致PC崩溃问题求助

解决gmpy2与numpy object数组循环中的内存泄漏问题

你的代码中内存持续累积的核心原因是numpy object数组中存储的gmpy2对象未被及时垃圾回收。虽然你没有保存矩阵的引用,但numpy的object数组会持有每个gmpy2元素的引用,加上Jupyter环境的特性(变量可能被隐式保留),导致Python的垃圾回收机制无法及时释放这些内存。另外,gmpy2的上下文管理也可能残留未清理的资源。

以下是几种有效的解决办法:

方法1:手动触发垃圾回收

在每次循环结束后显式调用gc.collect(),强制Python回收未使用的内存:

import numpy as np
import gmpy2 as gp
import psutil, os, gc  # 引入gc模块


def get_matrix():
    n = 2**8 - 1
    mat = np.zeros((n, n), dtype=object)
    for i in range(n):
        for j in range(n):
            mat[i,j] = gp.cos(i*j)
    return mat


process = psutil.Process(os.getpid())

for _ in range(20):
    with gp.context(gp.get_context()) as context:
        context.precision = 123
        mat = get_matrix()  # 显式持有引用
        del mat  # 手动删除引用
    gc.collect()  # 强制垃圾回收
    memory_used_in_MB = process.memory_info().rss * 1e-6
    print(f'Memory used: {memory_used_in_MB}')

方法2:避免使用numpy object数组

numpy的object数组对存储Python对象(如gmpy2高精度数值)并不友好,容易引发引用问题。改用纯Python列表存储gmpy2元素,能减少内存泄漏风险:

import gmpy2 as gp
import psutil, os, gc


def get_matrix():
    n = 2**8 - 1
    mat = []
    for i in range(n):
        row = []
        for j in range(n):
            row.append(gp.cos(i*j))
        mat.append(row)
    return mat


process = psutil.Process(os.getpid())

for _ in range(20):
    with gp.context(gp.get_context()) as context:
        context.precision = 123
        mat = get_matrix()
        del mat
    gc.collect()
    memory_used_in_MB = process.memory_info().rss * 1e-6
    print(f'Memory used: {memory_used_in_MB}')

方法3:结合gmpy2内存清理

gmpy2的高精度对象依赖底层C库管理内存,虽然主要靠Python GC回收,但可以在循环中显式清理临时对象。配合前两种方法使用,能进一步降低内存残留:

# 在生成矩阵后,除了del mat,还可以手动清空上下文缓存(如果有)
context.clear_cache()  # gmpy2上下文的缓存清理方法

验证效果

使用上述方法后,内存会维持在稳定区间,不会持续累积,彻底避免因内存耗尽导致的系统冻结或蓝屏问题。

内容的提问来源于stack exchange,提问作者Octavius

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 16:45:13