具体步骤如下:
- 执行以下命令,打开位置,并创建脚本,如下图所示:
cd /usr/sz/
sudo vim cpu_usage.sh
2. 输入脚本内容如下:
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 $*
- 执行以下命令,查看cpu数目
cat /proc/cpuinfo | grep "processor"|wc -l
- 执行以下命令,运行脚本,表示消耗完1颗cpu资源
sh cpu_usage.sh consume 1
5.使用top命令,可以看到cpu到使用率占到100%;下图是我自己写的一个系统系能见识工具,可视化总体cpu使用率,我的服务器有2颗cpu,第4步将1颗cpu性能消耗完,所以使用率为50%,空闲率也是50%;
6.执行以下命令,释放所有构造的cpu占用进程,或者用kill命令杀死对应进程
sh cpu_usage.sh release