需求:服务器CPU使用率过低,增加CPU使用率到指定范围
1、安装cpulimit对 CPU 使用率进行控制
yum install gcc -y
wget 'http://downloads.sourceforge.net/cpulimit/cpulimit-1.1.tar.gz' --no-check-certificate
tar -zxf cpulimit-1.1.tar.gz
cd cpulimit-1.1
make
cp cpulimit /usr/bin/
# 使用
1)限制进程号的程序使用40% cpu利用率
cpulimit -p 1313 -l 40
2)限制程序google使用40% cpu利用率
cpulimit -e google -l 40
2、shell脚本增加CPU压力:cputest.sh
#! /bin/bash
# filename cputest.sh
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 'stopUsage: kill ' $i ';';
done
3、执行增加CPU压力的脚本,然后控制观察
# chmod +x cputest.sh
#几核CPU就写几
# sh cputest.sh 1
stopUsage: kill 21648 ;
# top
# 限制进程号21648使用的CPU利用率为40%
# cpulimit -p 21648 -l 40 &
#中断脚本
# kill 21648
PS:增加CPU后限制使用率到指定值40%整合脚本:
#! /bin/bash
# filename cputest.sh
# 限制进程号的程序使用40% cpu利用率(可修改)
utilization="40"
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 'stopUsage: kill ' $i ';'
nohup cpulimit -p "$i" -l "$utilization" &
done
运行结果如下:
[root@web ~]# bash cputest.sh 2
stopUsage: kill 35045 ;
stopUsage: kill 35047 ;
You have new mail in /var/spool/mail/root
[root@web ~]# nohup: appending output to ‘nohup.out’
nohup: appending output to ‘nohup.out’
[root@web ~]# ps -ef | grep limit
root 35048 1 0 00:11 pts/0 00:00:00 cpulimit -p 35045 -l 40
root 35049 1 0 00:11 pts/0 00:00:00 cpulimit -p 35047 -l 40
[root@web ~]# top
top - 00:12:32 up 1 day, 15:18, 5 users, load average: 1.26, 0.63, 0.30
Tasks: 125 total, 4 running, 121 sleeping, 0 stopped, 0 zombie
%Cpu0 : 40.5 us, 0.0 sy, 0.0 ni, 59.5 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
%Cpu1 : 40.8 us, 0.0 sy, 0.0 ni, 59.2 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 st
KiB Mem : 997956 total, 259040 free, 147584 used, 591332 buff/cache
KiB Swap: 2097148 total, 2096884 free, 264 used. 616408 avail Mem
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
35045 root 20 0 113280 1200 1020 R 39.2 0.1 0:15.19 bash
35047 root 20 0 113280 1200 1020 R 39.2 0.1 0:15.20 bash