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

2022-06-10  本文已影响0人  孙广宁
13.14 我们相对运行的程序占用的CPU和内存设定一个限制
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
def limit_memory(maxsize):
    soft,hard = resource.getrlimit(resource.RLIMIT_AS)
    resource.setrlimit(resource.RLIMIT_AS,(maxsize,hard))
上一篇下一篇

猜你喜欢

热点阅读