背景
提出两个需求
占满系统CPU占用大内存
通过上网查资料,做实验使用Python实现了上述两个需求。
先看效果
执行前
内存
CPU
执行后
内存
CPU
代码实现
环境说明:代码使用Python3实现
#! /user/bin/env python# -*- encoding: utf-8 -*-import sysimport reimport timefrom multiprocessing import Process,cpu_countdef print_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')#实现占用内存def mem():pattern = pile('^(\d*)([M|G]B)$')size = sys.argv[2].upper()match = pattern.match(size)if match: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满载def deadloop():while True:pass#根据传参来指定占满几个核def cpu():arg = sys.argv[2] if len(sys.argv) == 3 else sys.argv[3]cpu_num = cpu_count()cores = int(arg)if not isinstance(cores,int):print("bad args not int")returnif cores > cpu_num:print("Invalid CPU Num(cpu_count="+str(cpu_num)+")")returnif cores is None or cores <1:cores = 1for i in range(cores):Process(target=deadloop).start()def mem_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占用2GBpython3 test_mem.py mc 2GB 2
Linux命令查看
//查看内存$ free -h//查看CPU,每秒采集一次,共5次$ sar -u 1 5