用Python实现Linux系统占用指定内存,CPU满载,服务器压力测试,场景设计

背景

提出两个需求

  1. 占满系统CPU
  2. 占用大内存

通过上网查资料,做实验使用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

 

猜你喜欢

转载自www.cnblogs.com/guixie/p/11834707.html