centos7限制CPU使用率-cpulimit
一、背景
有的进程长时间占用CPU较大,拖垮了其他进程。所以有必要限制CPU的使用率
二、CPU使用率限制方案
采用以下工具限制CPU使用率:
- 开源工具cpulimit
- shell脚本实现
三、操作
(一)安装cpulimit
1、下载
优先下载:https://sourceforge.net/projects/cpulimit/
如果不能下载了,使用备用源文件:https://www.cnblogs.com/andy9468/p/15357524.html
项目地址:https://hub.fastgit.org/opsengine/cpulimit/releases
2、编译、安装
https://blog.csdn.net/weixin_34061482/article/details/90595276
tar -zcvf cpulimit-1.1.tar.gz
cd cpulimit-1.1
make
# 安装
cp cpulimit /usr/bin
chmod 777 /usr/bin/cpulimit
3、测试
cpulimit --help
4、cpulimit的常见使用
https://blog.csdn.net/weixin_39731623/article/details/111763124
https://www.cnblogs.com/luruiyuan/p/12676758.html
# 将pid为39929的进程,cpu的使用率限制到50%以内
cpulimit -p 39929 -l 50
(二)编写shell脚本、编写测试脚本
1、shell限制脚本
# 限制CPU占用率大于50%的进程
for x in `ps -aux|awk '{if($3 > 50) print $2}'`; do cpulimit -p $x -l 50; done
展开解释
for x in `ps -aux|awk '{if($3 > 50) print $2}'`;
do
cpulimit -p $x -l 50;
done
当某些进程的CPU占用(第3列)率大于50%时,取出进程pid号(第2列),在for循环中将其CPU的使用率限制到50%以内。
2、python测试脚本
cpu_test.py
import os
import time
def add2():
sum_int = 1
start_time = time.time()
for i in range(1000000):
sum_int = sum_int * (i + 1)
pass
end_time = time.time()
use_time = end_time - start_time
print("进程id: %s use_time: %s" % (os.getpid(), use_time))
print(sum_int)
if __name__ == '__main__':
add2()
(三)测试CPU限制效果
1、启动python测试脚本
python3 cpu_test.py
提示:当python3进程被限制使用CPU后,会被放到后台运行。解除限制后,fg命令多次,可以调出改进程。
2、启动shell限制脚本
for x in `ps -aux|awk '{if($3 > 50) print $2}'`; do cpulimit -p $x -l 50; done
3、htop观察CPU占用情况
htop