Linux中使用cpulimit 限制 cpu 占用率
什么是cpulimit?
cpulimit 命令的工作原理是为进程预设一个 cpu 占用率门限,并实时监控进程是否超出此门限,若超出则让该进程暂停运行一段时间。cpulimit 使用 SIGSTOP 和 SIGCONT 这两个信号来控制进程。它不会修改进程的 nice 值,而是通过监控进程的 cpu 占用率来做出动态调整。
cpulimit 的优势是可以控制进程的cpu使用率的上限值。但与 nice 相比也有缺点,那就是即使 cpu 是空闲的,进程也不能完全使用整个 cpu 资源。
安装
https://github.com/opsengine/cpulimit/archive/master.zip
unzip cpulimit.zip
cd cpulimit-master
make
cp src/cpulimit /usr/bin
make过程当中出现如下两个报错:
原因:因为较新的 Linux 内核版本中已经弃用了 sysctl.h
头文件。
解决: 打开 cpulimit.c
文件:
- 找到并注释掉或删除
#include <sys/sysctl.h>
行。
问题描述:由于预处理器条件语法不正确导致的报错。
解决:
#匹配到45行修改为以下语法
#if defined(__APPLE__) || defined(__FREEBSD__)
成功解决!!
什么是stress?
stress⼯具是Linux下一款压⼒测试⼯具, 可以模拟系统⾼负载运⾏ , 同时可协助我们进⾏软件稳 定性相关测试。
安装
下载地址: https://fossies.org/linux/privat/stress-1.0.4.tar.gz
2 sudo tar -zxvf stress-1.0.4.tar.gz
3 cd stress-1.0.4/
4 ./condfigure
5 make
6 make check
7 make install
8 安装完毕~
9 stress --version
10 终端显⽰: stress 1.0.4 安装成功
报错解决:
描述: 由于系统时间不正确导致
sudo systemctl start chronyd
sudo systemctl enable chronyd
sudo chronyc makestep
安装完成:
[root@k8s-master stress-ng-0.18.11]# stress-ng --version
stress-ng, version 0.18.11 (gcc 10.3.1, x86_64 Linux 5.10.0-136.12.0.86.oe2203sp1.x86_64) 💻🔥
案例测试:
使用stress命令生成 CPU 负载并运行指定的时间
[root@k8s-master stress-ng-0.18.11]# stress-ng --cpu 1 --timeout 300 &
[1] 124157
[root@k8s-master stress-ng-0.18.11]# stress-ng: info: [124157] setting to a 5 mins run per stressor
stress-ng: info: [124157] dispatching hogs: 1 cpu
stress-ng: info: [124157] note: system has only 363 MB of free memory and swap, recommend using --oom-avoid
使用cpulimit工具通过进程pid限制cpu:
[root@k8s-master stress-ng-0.18.11]# sudo cpulimit -p 124158 -l 50
Process 124158 found
使用top命令查看cpu使用率