美文网首页
python resource模块设置内存、CPU使用量

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

作者: 孙广宁 | 来源:发表于2022-06-10 23:47 被阅读0次
    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异常

    相关文章

      网友评论

          本文标题:python resource模块设置内存、CPU使用量

          本文链接:https://www.haomeiwen.com/subject/fclimrtx.html