一、CPU使用率

1、脚本准备

您需要在 指定的服务器目录新建一个文件,即一个shell脚本,当运行其脚本时,服务器的cpu使用率会根据配置的参数做相应的提高

cd /opt
vim cpu.sh

然后将以下内容粘贴至文件中,并保存

#!/bin/bash

FILE_NAME=`basename $0`
cpunum=$2
pid_array=()
function usage()
{
echo "Usage:$FILE_NAME consume cpu_number|release -----the value of cpu_number is an integer,such as 1,2,3"
echo "Example: $FILE_NAME consume 12"
echo "         $FILE_NAME release"
}
 
function endless_loop()
{
echo -ne "i=0;
while true
do
    i=i+100;
    i=100
done" | /bin/bash &
}
 
 
function consume()
{
for i in `seq $1`
do
    endless_loop
    pid_array[$i]=$!
done
echo "consume cpu resources process ids are: ${pid_array[*]}"
}
 
function release()
{
for pid in $(ps -ef |grep /bin/bash |grep -v grep |awk '{print $2}' |xargs)
do
    kill -9 $pid
done
}
 
function main()
{
case "$1" in
    consume) consume $cpunum;;
    release) release;;
          *) usage;exit 1;;
esac
}
 
main $*

2、运行脚本

然后保存文件,运行此shell脚本

sh cpu.sh consume 所需要占用的cpu核数

注意:在运行该脚本时,需要先确认当前服务器的cpu核数之后在运行,以免出现CPU使用率太高导致服务器宕机,例如当前服务器的配置为8核16G,需要将服务器的cpu使用率提高至30%-40%,你需要使用该脚本运行占用3核CPU,以达到服务器CPU资源使用率达到30%的目的,此时是运行脚本的运行命令为:

sh cpu.sh consume 3

3、资源回收

当需要更换CPU占用资源大小时,需要先将原先占用的资源回收后再运行资源占用,资源释放命令:

sh cpu.sh release

二、内存使用率

1、脚本准备

您需要在 指定的服务器目录新建一个文件,即一个shell脚本,当运行其脚本时,服务器的内存使用率会根据配置的参数做相应的提高

cd /opt
vim memory.sh

然后将以下内容粘贴至文件中,并保存

#!/bin/bash

FILE_NAME=`basename $0`
memsize=$2
function usage()
{
echo "Usage:$FILE_NAME consume memory_size|release -----the value of memory_size like 100M 2G and etc"
echo "Example: $FILE_NAME consume 1G"
echo "         $FILE_NAME release"
}
function consume()
{
if [ -d  /tmp/memory ];then
    echo "/tmp/memory already exists"
else
    mkdir /tmp/memory
fi
mount -t tmpfs -o size=$1 tmpfs /tmp/memory   
dd if=/dev/zero of=/tmp/memory/block
 
}
 
function release()
{
rm /tmp/memory/block;ret=$?
if [ $ret != 0 ]; then
    echo "remove memory data failed"
    return $ret
fi
 
umount /tmp/memory;ret=$?
if [ $ret != 0 ]; then
    echo "umount memory filedir failed"
    return $ret
fi
 
rmdir /tmp/memory;ret=$?
if [ $ret != 0 ]; then
    echo "remove memory filedir failed"
    return $ret
fi
 
}
 
function main()
{
case "$1" in
    consume) consume $memsize;;
    release) release;;
          *) usage;exit 1;;
esac
}
 
main $*

2、脚本运行

然后保存文件,运行此shell脚本

sh memory.sh consume 所需要占用的内存

注意:在运行该脚本时,需要先确认当前服务器的内存大小之后在运行,以免出现内存使用率太高导致服务器宕机,例如当前服务器的配置为8核16G,需要将服务器的内存使用率提高至30%-40%,你需要使用该脚本运行占用5G,以达到服务器内存资源使用率达到30%的目的,此时是运行脚本的运行命令为:

sh memory.sh consume 5G

3、资源回收

当需要更内存占用资源大小时,需要先将原先占用的资源回收后再运行资源占用,资源释放命令:

sh memory.sh release
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐