日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

python如何給內(nèi)存和cpu使用量設(shè)置限制_python

作者:小平愛吃肉 ? 更新時間: 2022-07-09 編程語言

給內(nèi)存和cpu使用量設(shè)置限制

在linux系統(tǒng)中,使用Python對內(nèi)存和cpu使用量設(shè)置限制需要通過resource模塊來完成。

resource文檔地址:resource — Resource usage information

限制Python進(jìn)程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))

原文鏈接:https://blog.csdn.net/qq_32188669/article/details/107966322

欄目分類
最近更新