python如何給內(nèi)存和cpu使用量設(shè)置限制
給內(nèi)存和cpu使用量設(shè)置限制
在linux系統(tǒng)中,使用Python對內(nèi)存和cpu使用量設(shè)置限制需要通過resource模塊來完成。
resource文檔地址:resource — Resource usage information
限制Python進程cpu使用時間的樣例如下
import signal import resource import os def time_exceeded(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_exceeded) if __name__ == '__main__': ? ? set_max_runtime(5) ? ? while True: ? ? ? ? pass
運行上述代碼,當(dāng)超時時會產(chǎn)生SIGXCPU信號。程序就會做清理工作然后退出。
要限制內(nèi)存的使用可以使用如下函數(shù)
def limit_memory(maxsize): ? ? soft, hard = resource.getrlimit(resource.RLIMIT_AS) ? ? resource.setrlimit(resource.RLIMIT_AS, (maxsize, hard))
當(dāng)設(shè)定了內(nèi)存限制后,如果沒有更多的內(nèi)存可用,程序就會開始產(chǎn)生MemoryError異常。
注:以上示例代碼來源于:《Python Cookbook》P575 “給內(nèi)存和cpu使用量設(shè)置限制”。
查詢windows的cpu、內(nèi)存使用率
# -*- coding: UTF-8 -*- import os def get_info(metric): ? ? metric_cmd_map = { ? ? ? ? "cpu_usage_rate": "wmic cpu get loadpercentage", ? ? ? ? "mem_total": "wmic ComputerSystem get TotalPhysicalMemory", ? ? ? ? "mem_free": "wmic OS get FreePhysicalMemory" ? ? } ? ? out = os.popen("{}".format(metric_cmd_map.get(metric))) ? ? value = out.read().split("\n")[2] ? ? out.close() ? ? return float(value) # cpu使用率 cpu_usage_rate = get_info('cpu_usage_rate') print("windows的CPU使用率是{}%".format(cpu_usage_rate)) # 無法直接查出內(nèi)存使用率,總內(nèi)存單位是b,而剩余內(nèi)存單位是kb mem_total = get_info('mem_total')/1024 mem_free = get_info('mem_free') mem_usage_rate = (1 - mem_free/mem_total)*100 print("windows的內(nèi)存使用率是{}%".format(mem_usage_rate))
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
從零學(xué)Python之入門(二)基本數(shù)據(jù)類型
這是繼“hello world”之后的第二篇入門級基礎(chǔ)知識,以后這個系列會按照入門、進階、精通三個分類進行下去,歡迎高手們來拍磚2014-05-05python實現(xiàn)翻轉(zhuǎn)棋游戲(othello)
這篇文章主要為大家詳細介紹了python實現(xiàn)翻轉(zhuǎn)棋游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07