使用cpulimit 控制进程CPU占用率

cpulimit 命令的工作原理是为进程预设一个 cpu 占用率门限,并实时监控进程是否超出此门限,若超出则让该进程暂停运行一段时间。cpulimit 使用 SIGSTOP 和 SIGCONT 这两个信号来控制进程。它不会修改进程的 nice 值,而是通过监控进程的 cpu 占用率来做出动态调整。

cpulimit 的优势是可以控制进程的cpu使用率的上限值。但与 nice 相比也有缺点,那就是即使 cpu 是空闲的,进程也不能完全使用整个 cpu 资源。

cpulimit安装

wget https://github.com/opsengine/cpulimit/archive/refs/tags/v0.2.tar.gz

tar xf v0.2.tar.gz

cd cpulimit-0.2/src/

make

cp cpulimit /usr/bin/

cpulimit命令使用语法

cpulimit [OPTIONS...] TARGET

[OPTIONS]:

      -l, --limit=N          percentage of cpu allowed from 0 to 200 (required) # 限制数值

      -v, --verbose          show control statistics # 显示控制统计信息

      -z, --lazy             exit if there is no target process, or if it dies

      -i, --include-children limit also the children processes  # 同时限制子进程

      -h, --help             display this help and exit  # 打印帮助信息

   TARGET must be exactly one of these:

      -p, --pid=N            pid of the process (implies -z)   # 指导PID

      -e, --exe=FILE         name of the executable program file or path name

举例说明:

我要限制PID为3269的进程只占用cpu 60%的资源,我该怎么做呢?

cpulimit -p 3269 -l 60

我们执行命令时还可以加-v参数来统计控制信息

cpulimit工具的原理就是进程在R->T状态之间不停转换来限制资源

posted @ 2025-03-26 19:36  杨灏  阅读(406)  评论(0)    收藏  举报