Skip to content

antony@notes:~/misc$ cat "Limit-CPU-Usage-of-a-Process-on-Linux.md"

Limit CPU Usage of a Process on Linux

2022-08-13· misc

How to Limit CPU Usage of a Process on Linux

:::warning

:::spoiler 目錄

[TOC]

:::

Limiting CPU Usage with nice and renice:

  • nice 值
    • 決定了哪個程序具有更高的優先級,哪個具有更低的優先級。
    • nice 值為 -20 的程序將具有最高優先級,並且將使用最多的 CPU 週期。
    • nice 值為 19 的程序將具有最低優先級,並且將在沒有其他程序僅使用它時使用 CPU。
    • Nice 值可以在 -20 到 19 之間。

使用 nice 命令啟動一個程序

$ nice -n NICE_VALUE COMMAND_TO_RUN
  • -n--adjustment=N, 設定 nice 的值,預設是 10
  • NICE_VALUE ,nice 值,可以是 -20 到 19 之間的任何值
  • COMMAND_TO_RUN ,要執行的命令

sleep 命令的 nice 值 設為 10

$ nice -n 10 sleep 60 &
[1] 56860

檢查

$ ps -fl
F S UID         PID   PPID  C PRI  NI ADDR SZ WCHAN  STIME TTY          TIME CMD
0 S bigred     4009   4008  0  80   0 -   663 -      00:57 pts/1    00:00:00 -bash
0 S bigred    56860   4009  0  90  10 -   669 -      15:39 pts/1    00:00:00 sleep 60
0 R bigred    56880   4009  0  80   0 -   427 -      15:39 pts/1    00:00:00 ps -fl

注意 ! nice 值設定小於 0 ,需要管理員的權限

$ nice -n -1 sleep 60 &
nice: cannot set niceness: Permission denied

設定已經在跑的程序

$ sudo renice -n NEW_NICE_VALUE -p PROCESS_PID
  • -n ,設定 nice 值
  • -p ,設定要重新指定 nice 值的 process 的 PID
# 設定 nice 值為 10 的 sleep 命令
$ nice -n 10 sleep 600 &

# 檢查
$ ps -fl
F S UID         PID   PPID  C PRI  NI ADDR SZ WCHAN  STIME TTY          TIME CMD
0 S bigred     4009   4008  0  80   0 -   792 -      00:57 pts/1    00:00:00 -bash
0 S bigred    57412   4009  0  90  10 -   669 -      15:48 pts/1    00:00:00 sleep 600
0 R bigred    57470   4009  0  80   0 -   427 -      15:49 pts/1    00:00:00 ps -fl

# 重新設定 sleep 命令的 nice 值為 5
$ sudo renice -n 5 -p 57412
57412 (process ID) old priority 10, new priority 5

# 檢查是否符合預期
$ ps -fl
F S UID         PID   PPID  C PRI  NI ADDR SZ WCHAN  STIME TTY          TIME CMD
0 S bigred     4009   4008  0  80   0 -   792 -      00:57 pts/1    00:00:00 -bash
0 S bigred    57412   4009  0  85   5 -   669 -      15:48 pts/1    00:00:00 sleep 600
0 R bigred    57500   4009  0  80   0 -   427 -      15:50 pts/1    00:00:00 ps -fl

使用 CGROUPS 限制 CPU 使用率

在 Alpine Linux 3.16.1 安裝套件

$ sudo apk add cgroup-tools