温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python怎么给内存和cpu使用量设置限制

发布时间:2022-05-16 13:44:57 来源:亿速云 阅读:269 作者:iii 栏目:开发技术

本篇内容介绍了“python怎么给内存和cpu使用量设置限制”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

    给内存和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))

    “python怎么给内存和cpu使用量设置限制”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

    向AI问一下细节

    免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

    AI