推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
HawkinsSherpherd
V2EX  ›  Python

有什么好办法限制 Python 的内存分配吗?

  •  1
     
  •   HawkinsSherpherd · Jan 4, 2025 · 6394 views
    This topic created in 633 days ago, the information mentioned may be changed or developed.

    这是一段会吃掉几乎所有可用内存的代码:

    def Decompress_Gzip_With_Progress_Bar(gzip_path, output_path):
        with gzip.open(gzip_path, 'rb') as f_in:
            with open(output_path, 'wb') as f_out:
                file_size = Get_Uncompressed_Size(gzip_path)
                chunk_size = 1024 * 1024
                with tqdm(total=file_size, unit='B', unit_scale=True, desc="Decompressing " + gzip_path) as pbar:
                    for block in iter(lambda: f_in.read(chunk_size), b''):
                        f_out.write(block)
                        pbar.update(len(block))
    

    它被用于解压一个解压后大概 4G 大小的文件。

    直接在我的 16G 内存的开发虚拟机上运行,它会吃掉所有的内存。

    但是,如果我把它放到一个分配 1G 内存的容器里,它不仅能运行,甚至还能运行得更快。

    我试过用 resource 限制内存分配,但是它还是会吃满所有内存。

    有没有什么能直接写到 Python 代码里的限制内存分配的方法呢?

    11 replies  •  2025-01-20 19:25:27 +08:00
    Donaldo
        1
    Donaldo  
       Jan 4, 2025
    和你的容器办法类似,但不用这么重,直接把这段代码丢进一个 cgroup 里面,这个 cgroup 限制好内存就行
    Donaldo
        2
    Donaldo  
       Jan 4, 2025
    Windows 没有 cgroup ,我找到一个工具:https://github.com/lowleveldesign/process-governor
    fighterhit
        3
    fighterhit  
       Jan 4, 2025   ❤️ 1
    那说明基本都是 cache 啊,如果 rss 常驻内存应该早 oom 了
    paopjian
        4
    paopjian  
       Jan 4, 2025
    吃满内存的行为是操作系统的缓存吧, 如果其他程序再需要,会清理内容?
    sagaxu
        5
    sagaxu  
       Jan 4, 2025
    循环内加入强制 gc 试试

    pbar.update(len(block))
    gc.collect()
    zsj1029
        6
    zsj1029  
       Jan 4, 2025 via iPhone
    只要不会 oom 就不用管吧
    jimrok
        7
    jimrok  
       Jan 6, 2025
    看这个代码是不是把文件全部读入内存去解压,如果内存不足,可能要 OOM ,是否能改成流式处理?
    lshu
        8
    lshu  
       Jan 7, 2025
    f_out.write(block) 这行后面接一个 f_out.flush() 方法,内存写到硬盘中
    Maerd
        9
    Maerd  
       Jan 15, 2025
    这种大文件,就不适合在内存中操作,正确的方法是使用虚拟内存
    import mmap
    可以将直接将一个硬盘文件变为虚拟内存
    这样的进行写入的好处不只是省内存,还减少了一次用户态和内核态之间的切换
    beyondstars
        10
    beyondstars  
       Jan 20, 2025
    这种压缩解压缩的任务为什么不用流 (stream) 式操作?
    hotea
        11
    hotea  
       Jan 20, 2025
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5429 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 03:22 · PVG 11:22 · LAX 20:22 · JFK 23:22
    ♥ Do have faith in what you're doing.