參加過各種 online judge 的同學(xué)肯定知道惕它,一般每道編程題都會有運算時間限制和內(nèi)存限制曾棕。在python中油昂,我們可以使用resource模塊來實現(xiàn)。
限制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
限制內(nèi)存
def limit_memory(maxsize):
soft, hard = resource.getrlimit(resource.RLIMIT_AS)
resource.setrlimit(resource.RLIMIT_AS, (maxsize, hard))