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

學無先后,達者為師

網站首頁 編程語言 正文

python如何給內存和cpu使用量設置限制_python

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

給內存和cpu使用量設置限制

在linux系統中,使用Python對內存和cpu使用量設置限制需要通過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

運行上述代碼,當超時時會產生SIGXCPU信號。程序就會做清理工作然后退出。

要限制內存的使用可以使用如下函數

def limit_memory(maxsize):
? ? soft, hard = resource.getrlimit(resource.RLIMIT_AS)
? ? resource.setrlimit(resource.RLIMIT_AS, (maxsize, hard))

當設定了內存限制后,如果沒有更多的內存可用,程序就會開始產生MemoryError異常。

注:以上示例代碼來源于:《Python Cookbook》P575 “給內存和cpu使用量設置限制”。

查詢windows的cpu、內存使用率

# -*- 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))
# 無法直接查出內存使用率,總內存單位是b,而剩余內存單位是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的內存使用率是{}%".format(mem_usage_rate))

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

欄目分類
最近更新