> Linux服务器 > 性能测试 >

cpu测试shell脚本

思想:利用命令查到内核个数,使用死循环占用每一个内核资源,消耗cpu总资源

前半部分没有作条件表达式判断,有需求的可以自行添加

#! /bin/bash
#############################################################
#       this scripts for cpu usage testing
#       eg.  cpu_test.sh start  50 #start testing use 50% cpu
#       eg.  cpu_test.sh stop  #stop testing
#############################################################
op=$1
num=$2

mkcsp()
{

        touch ./killcpu.c
        echo 'int main(){while(1);return 0;}' > killcpu.c
        gcc -o out killcpu.c
        chmod +x ./out

}

start()
{
cpu_num=$(cat /proc/cpuinfo | grep "physical id" | wc -l)

for i in `seq 1 $(expr $num \* $cpu_num / 100)`
        do
            ./out &
        done

}

stop()
{
for i in $( ps -ef | grep './out'| grep -v grep | awk '{print $2}')
        do
                kill -9 $i
        done
rm -rf killcpu.c out
}

main()
{
if [ $op == "start" ]
then
        mkcsp
fi
        $op
}


main

朋友的脚本 ,我师父啊~

#!/bin/bash
# Destription: testing cpu usage performance
# Example    : sh cpu_usage.sh 12
# Remark     : cat /proc/cpuinfo | grep "processor"|wc -l    #12==>Get the number of processor
# Date       : 2015-1-12
# update     : 2015-1-12

endless_loop()
{
echo -ne "i=0;
while true
do
i=i+100;
i=100
done" | /bin/bash &
}

if [ $# != 1 ] ; then
  echo "USAGE: $0 <CPUs>"
  exit 1;
fi
for i in `seq $1`
do
  endless_loop
  pid_array[$i]=$! ;
done

for i in "${pid_array[@]}"; do
  echo 'kill ' $i ';';
done
 


(责任编辑:IT)