如何使用“setrlimit”限制内存使用?RLIMIT\u AS杀死得太快;RLIMIT\u DATA,RLIMIT\u RSS,RLIMIT\u STACK kill n

2024-06-10 08:27:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用setrlimit来限制我在Linux系统上的内存使用,以防止进程崩溃(我的代码在高性能集群上崩溃节点,因为一个bug导致内存消耗超过100gib)。我似乎找不到要传递给setrlimit的正确资源;我认为它应该是resident,即cannot be limited with setrlimit,但是我被resident、heap、stack搞糊涂了。在下面的代码中;如果我只取消了RLIMIT_AS的注释,那么即使该数组应该只有80MB,代码也会在MemoryError处失败。如果我只取消注释RLIMIT_DATARLIMIT_RSS或{}两个数组都会成功分配,即使总内存使用量是2GB,或者是所需最大值的两倍。在

我想让我的程序失败(无论如何),只要它试图分配太多的内存。为什么RLIMIT_DATARLIMIT_RSSRLIMIT_STACK和{}都不按我的意思做,传递给setrlimit的正确资源是什么?在

$ cat mwe.py 
#!/usr/bin/env python3.5

import resource
import numpy

#rsrc = resource.RLIMIT_AS
#rsrc = resource.RLIMIT_DATA
#rsrc = resource.RLIMIT_RSS
#rsrc = resource.RLIMIT_STACK

soft, hard = resource.getrlimit(rsrc)
print("Limit starts as:", soft, hard)

resource.setrlimit(rsrc, (1e9, 1e9))

soft, hard = resource.getrlimit(rsrc)
print("Limit is now:", soft, hard)
print("Allocating 80 KB, should certainly work")
M1 = numpy.arange(100*100, dtype="u8")

print("Allocating 80 MB, should work")
M2 = numpy.arange(1000*1000*10, dtype="u8")

print("Allocating 2 GB, should fail")
M3 = numpy.arange(1000*1000*250, dtype="u8")

input("Still here…")

未注释RLIMIT_AS行的输出:

^{pr2}$

与其他未注释的任何一个一起运行时的输出:

$ ./mwe.py 
Limit starts as: -1 -1
Limit is now: 1000000000 -1
Allocating 80 KB, should certainly work
Allocating 80 MB, should work
Allocating 2 GB, should fail
Still here…

在最后一行,top报告我的进程正在使用379gbvirt,2.0gbres


系统详细信息:

$ uname -a
Linux host.somewhere.ac.uk 2.6.32-573.3.1.el6.x86_64 #1 SMP Mon Aug 10 09:44:54 EDT 2015 x86_64 x86_64 x86_64 GNU/Linux

$ cat /etc/redhat-release 
Red Hat Enterprise Linux Server release 6.7 (Santiago)

$ free -h
             total       used       free     shared    buffers     cached
Mem:          2.0T       1.9T        37G       1.6G       3.4G       1.8T
-/+ buffers/cache:        88G       1.9T 
Swap:         464G       4.8M       464G 

$ python3.5 --version
Python 3.5.0

$ python3.5 -c "import numpy; print(numpy.__version__)"
1.11.1

Tags: 内存numpylinuxresourcex86worksoftlimit
1条回答
网友
1楼 · 发布于 2024-06-10 08:27:16

唉,你的问题我没有答案。但我希望以下几点可能会有所帮助:

  • 你的脚本在我的系统上正常工作。请分享您的确切规格,可能有一个已知的问题,Linux发行版,内核,甚至numpy。。。在
  • 您应该可以使用RLIMIT_AS。如前所述,here这应该限制进程使用的整个虚拟内存。虚拟内存包括:交换内存、共享库、代码和数据。更多详细信息here。在
  • 您可以在脚本中添加以下函数(从this answer)来检查实际的虚拟内存使用情况:

    def peak_virtual_memory_mb():
        with open('/proc/self/status') as f:
            status = f.readlines()
            vmpeak = next(s for s in status if s.startswith("VmPeak:"))
            return vmpeak
    
  • 一般建议,禁用交换内存。根据我对高性能服务器的经验,它带来的危害大于解决问题。在

相关问题 更多 >