python resource模块设置内存、CPU使用量

13.14 我们相对运行的程序占用的CPU和内存设定一个限制
  • resource模块可以用来执行这样的任务。

import signal
import resource
import os

def time_exceeded(signo,frame):
    print("Times UP")
    raise SystemExit(1)

def set_max_runtime(seconds):
    soft,hard =resource.getrlimit(resource.RLIMIT_CPU)
    resource.setrlimit(resource.RLIMIT_CPU,(seconds,hard))
    signal.signal(signal.SIGXCPU,time_exceeded)

def __name__ ==  __main__ :
    set_max_runtime(15)
    while True:
        pass

  • 运行上述代码时,当超时时会产生SIGXCPU信号,程序会自动清理退出。
  • 要想限制内存使用,可以使用总地址空间上设定一个限制

def limit_memory(maxsize):
    soft,hard = resource.getrlimit(resource.RLIMIT_AS)
    resource.setrlimit(resource.RLIMIT_AS,(maxsize,hard))

  • 当达到设定的内存限制后,如果没有更多的内存可以使用,程序会产生MemoryError异常
© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容