背景
提出两个需求
占满系统CPU
占用大内存
通过上网查资料,做实验使用Python实现了上述两个需求。
先看效果
执行前
内存
CPU
执行后
内存
CPU
代码实现
环境说明:代码使用Python3实现
#! /user/bin/env python#-*- encoding: utf-8 -*-
importsysimportreimporttimefrom multiprocessing importProcess,cpu_countdefprint_help():print('Usage:')print('python test_mem.py m 1GB')print('python test_mem.py c 1')print('python test_mem.py mc 1GB 2')#实现占用内存
defmem():
pattern= re.compile('^(\d*)([M|G]B)$')
size= sys.argv[2].upper()
match=pattern.match(size)ifmatch:
num= int(match.group(1))
unit= match.group(2)if unit == 'MB':
s= ' ' * (num * 1024 * 1024)else:
s= ' ' * (num * 1024 * 1024 * 1024)
time.sleep(24 * 3600)else:print("bad args.....")
print_help()#cpu满载
defdeadloop():whileTrue:pass
#根据传参来指定占满几个核
defcpu():
arg= sys.argv[2] if len(sys.argv) == 3 else sys.argv[3]
cpu_num=cpu_count()
cores=int(arg)if notisinstance(cores,int):print("bad args not int")return
if cores >cpu_num:print("Invalid CPU Num(cpu_count="+str(cpu_num)+")")return
if cores is None or cores <1:
cores= 1
for i inrange(cores):
Process(target=deadloop).start()defmem_cpu():
Process(target=mem).start()
Process(target=cpu).start()if __name__ == "__main__":if len(sys.argv) >= 3:
switcher={'m': mem,'c': cpu,'mc': mem_cpu
}
switcher.get(sys.argv[1], mem)()else:
print_help()
使用命令
//指定Mem占用,使用time.sleep()硬代码1天时间
python3 test_mem.py m 1GB
//CPU满载
python3 test_mem.py c 2
//CPU 2核满载,并且指定Mem占用2GB
python3 test_mem.py mc 2GB 2
Linux命令查看
//查看内存 $ free -h //查看CPU,每秒采集一次,共5次 $ sar -u 1 5
————————————————
版权声明:本文为CSDN博主「yuexue0」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yuexue0/article/details/86564253