通过shell脚本消耗cpu与内存

Posted by 煮石山农2024 - Jan - 06 Leave comments

1. 消耗内存脚本memory_usage.sh

1.1. Shell代码

#!/bin/bash
# Destription: testing memory usage 
# Example    : sh memory_usage.sh 500M | sh memory_usage.sh 1G | sh memory_usage.sh release

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 $*

1.2. 使用方法

需要以root权限执行。

sh memory_usage.sh consume {内存大小}

如:

memory_usage.sh consume 1G    # 即消耗1G 的内存

取消内存消耗:

sh memory_usage.sh release

2. 消耗CPU脚本cpu_usage.sh

2.1. Shell代码

#!/bin/bash
# Destription: test cpu usage 
# Example    : sh cpu_usage.sh consume 8 | sh cpu_usage.sh release

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.2. 使用方法

使用之前使用命令先查询下CPU的个数:

cat /proc/cpuinfo | grep "processor"|wc -l

grep processor /proc/cpuinfo |wc -l

需要构造消耗2颗CPU的资源运行脚本:

sh cpu_usage.sh consume 2

此时运行top命令查看CPU的使用率。

如果要释放CPU资源,运行:

sh cpu_usage.sh release

即可释放cpu资源。

   声明:本文采用 BY-NC-SA 协议进行授权 | 星期九
   原创文章转载请注明:转自《通过shell脚本消耗cpu与内存

No comments yet.
comment_ad
  

 NOTICE1: You should type some Chinese word in your comment to pass the spam-check, thanks for your patience!