参考:
http://www.codebaoku.com/it-python/it-python-248154.html
https://zhuanlan.zhihu.com/p/150234283
linux
# -*- coding: utf-8 -*-
"""
@Author :Mart
@Time :2022/7/25 15:33
@version :Python3.7.4
@Software:pycharm2020.3.2
"""
import resource
import time
import psutil
p = psutil.Process()
print(p.pid)
def limit_memory(maxsize):
soft, hard = resource.getrlimit(resource.RLIMIT_AS)
resource.setrlimit(resource.RLIMIT_AS, (maxsize, hard))
limit_memory(1024 * 1024 * 1800) # 限制180M ,可申请内存,对应虚拟内存
lst = []
while True:
lst.append("a" * 1000000)
time.sleep(0.5)
执行脚本后,程序会输出自己的进行pid,使用命令 top -p pid, 就可以查看到这个进程的资源使用情况,重点关注VIRT 的数值,这个是虚拟内存,resource模块限制的正是这个数值,这个数值在显示时默认是字节,按一下e 键,就可以切换单位,切换到m更容易观察,当VIRT接近180M或者略微超出时,进程就被kill了。
这里有必要解释一下,为什么VIRT 小于所限制的数值时进程会被kill。我在程序里使用列表不停的append字符串,python里的列表与C++ STL 里的vector有一点像,列表会先申请一部分内存,当这部分内存快耗尽时,它会依据算法申请一块更大的内存备用,当VIRT 接近180M时,已经申请的内存不够用了,于是python再次申请,结果一下子超过了180M,终端来没有来得及显示最终的内存量,进程就被kill了。
resource.setrlimit 可以限制python进行对资源的使用,resource.RLIMIT_AS 是 进程可能占用的地址空间的最大区域,单位是字节,soft 和 hard 的数值,你不必去关心,在linux下,默认都是-1,其实getrlimit方法可以不调用,直接将hard替换成-1就行。
windows
# -*- coding: utf-8 -*-
"""
@Author :Mart
@Time :2022/7/25 15:33
@version :Python3.7.4
@Software:pycharm2020.3.2
"""
# -*- 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))