文件名称:限制内存和CPU的使用量-python cookbook(第3版)高清中文完整版
文件大小:4.84MB
文件格式:PDF
更新时间:2024-06-29 23:06:51
python cookbook 第3版 高清 中文完整版
13.14 限制内存和CPU的使用量 问题 You want to place some limits on the memory or CPU use of a program running on Unix system. 解决方案 The resource module can be used to perform both tasks. For example, to restrict CPU time, do the following: 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 When this runs, the SIGXCPU signal is generated when the time expires. The program can then clean up and exit. To restrict memory use, put a limit on the total address space in use. For example: import resource def limit_memory(maxsize): soft, hard = resource.getrlimit(resource.RLIMIT_AS) resource.setrlimit(resource.RLIMIT_AS, (maxsize, hard))