这期内容当中小编将会给大家带来有关如何使用Python限制CPU使用量和内存,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
解决方案
resource 模块能同时执行这两个任务。例如,要限制CPU时间,可以像下面这样做:
import signal import resource import os def time_exceeded(signo, frame): print("Time's up!") raise SystemExit(1) def set_max_runtime(seconds): # Install the signal handler and set a resource limit soft, hard = resource.getrlimit(resource.RLIMIT_CPU) resource.setrlimit(resource.RLIMIT_CPU, (seconds, hard)) signal.signal(signal.SIGXCPU, time_exceeded) if __name__ == '__main__': set_max_runtime(15) while True: pass