背景
提出兩個需求
- 占滿系統CPU
- 占用大內存
通過上網查資料,做實驗使用Python實現了上述兩個需求。
先看效果
執行前
內存
CPU

執行后
內存

CPU

代碼實現
環境說明:代碼使用Python3實現
#! /user/bin/env python # -*- encoding: utf-8 -*- import sys import re import time from multiprocessing import Process,cpu_count def 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 = re.compile('^(\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") 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 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占用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

