cpuの時間とメモリの使用を制限する

745 ワード

様々な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))