Python限制内存和cpu使用量的操作是什么
Admin 2022-09-02 群英技术资讯 522 次浏览
在linux系统中,使用Python对内存和cpu使用量设置限制需要通过resource模块来完成。
resource文档地址:resource — Resource usage information
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使用量设置限制”。
# -*- 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))
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
python开发中经常遇到报错的情况,但是warning通常并不影响程序的运行,而且有时特别讨厌,下面我们来说下如何忽略warning错误。在说忽略wa
python怎样实现九宫格图片?我们常常能在朋友圈看到一张图片分成九宫格的图片,很多朋友都觉得挺有意思的,那么这是怎样做的呢?下面我们就来看看用Python怎样实现九宫格图片功能。
这篇文章主要介绍了Python数据分析之PMI数据图形展示,文章介绍了简单的python爬虫,并使用numpy进行了简单的数据处理,最终使用 matplotlib 进行图形绘制,实现了直观的方式展示制造业和非制造业指数图形,需要的朋友可以参考一下
这篇文章主要介绍了通过Pygame模块实现监听鼠标的功能,文章的示例代码讲解详细,对我们的学习或工作有一定的价值,感兴趣的小伙伴可以了解一下
这篇文章主要为大家介绍了python人工智能tensorflow函数tf.get_variable使用方法示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008