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

背景

提出两个需求

占满系统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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值