限制cpu时间和内存使用

参加过各种 online judge 的同学肯定知道,一般每道编程题都会有运算时间限制和内存限制。在python中,我们可以使用resource模块来实现。

限制cpu时间

import signal
import resource
import os

def time_excedded(signo, frame):
    print "time's 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_excedded)

if __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))

你可能感兴趣的:(限制cpu时间和内存使用)