一、限制可使用的CPU百分比
cpu.cfs_period_us:用來配置時間周期長度,單位微秒,取值范圍1ms至1s
cpu.cfs_quota_us:用來配置當前cgroup在設置的周期長度內所能使用的CPU時間數,單位微秒,取值大於1ms,-1代表不受限制
1.限制只能使用1個CPU # echo 250000 > cpu.cfs_quota_us # echo 250000 > cpu.cfs_period_us 2.限制使用2個CPU(內核) # echo 1000000 > cpu.cfs_quota_us # echo 500000 > cpu.cfs_period_us 3.限制使用1個CPU的20% # echo 10000 > cpu.cfs_quota_us # echo 50000 > cpu.cfs_period_us
二、cpu.shares
用來設置CPU的相對值,並且是針對所有的CPU(內核),默認值是1024,假如系統中有兩個cgroup,分別是A和B,A的shares值是1024,B的shares值是512,那么A將獲得1024/(1204+512)=66%的CPU資源,而B將獲得33%的CPU資源。shares有兩個特點
- 如果A不忙,沒有使用到66%的CPU時間,那么剩余的CPU時間將會被系統分配給B,即B的CPU使用率可以超過33%
- 如果添加了一個新的cgroup C,且它的shares值是1024,那么A的限額變成了1024/(1204+512+1024)=40%,B的變成了20%
從上面兩個特點可以看出:
- 在閑的時候,shares基本上不起作用,只有在CPU忙的時候起作用,這是一個優點。
- 由於shares是一個絕對值,需要和其它cgroup的值進行比較才能得到自己的相對限額,而在一個部署很多容器的機器上,cgroup的數量是變化的,所以這個限額也是變化的,自己設置了一個高的值,但別人可能設置了一個更高的值,所以這個功能沒法精確的控制CPU使用率。
三、cpu.stat
包含了下面三項統計結果
- nr_periods: 表示過去了多少個cpu.cfs_period_us里面配置的時間周期
- nr_throttled: 在上面的這些周期中,有多少次是受到了限制(即cgroup中的進程在指定的時間周期中用光了它的配額)
- throttled_time: cgroup中的進程被限制使用CPU持續了多長時間(納秒)
四、實例
# cd /sys/fs/cgroup/cpu # mkdir container # ls -l container/ total 0 -rw-r--r-- 1 root root 0 Nov 23 15:20 cgroup.clone_children --w--w--w- 1 root root 0 Nov 23 15:20 cgroup.event_control -rw-r--r-- 1 root root 0 Nov 23 15:20 cgroup.procs -r--r--r-- 1 root root 0 Nov 23 15:20 cpuacct.stat -rw-r--r-- 1 root root 0 Nov 23 15:20 cpuacct.usage -r--r--r-- 1 root root 0 Nov 23 15:20 cpuacct.usage_percpu -rw-r--r-- 1 root root 0 Nov 23 15:20 cpu.cfs_period_us -rw-r--r-- 1 root root 0 Nov 23 15:20 cpu.cfs_quota_us -rw-r--r-- 1 root root 0 Nov 23 15:20 cpu.rt_period_us -rw-r--r-- 1 root root 0 Nov 23 15:20 cpu.rt_runtime_us -rw-r--r-- 1 root root 0 Nov 23 15:20 cpu.shares -r--r--r-- 1 root root 0 Nov 23 15:20 cpu.stat -rw-r--r-- 1 root root 0 Nov 23 15:20 notify_on_release -rw-r--r-- 1 root root 0 Nov 23 15:20 tasks # cd container/ # more cpu.cfs_period_us #周期長度100ms 100000 # more cpu.cfs_quota_us #周期長度內可使用的CPU時間無限制 -1 # while : ; do : ; done & [1] 5969 # pidstat -p 5969 1 Linux 3.10.0-1062.9.1.el7.x86_64 (test-prd-10-47-4-40.gzyq.ts.lan) 11/23/2020 _x86_64_ (4 CPU) 03:24:01 PM UID PID %usr %system %guest %CPU CPU Command 03:24:02 PM 0 5969 99.00 0.00 0.00 99.00 3 bash 03:24:03 PM 0 5969 100.00 0.00 0.00 100.00 3 bash 03:24:04 PM 0 5969 100.00 0.00 0.00 100.00 3 bash 03:24:05 PM 0 5969 100.00 0.00 0.00 100.00 3 bash # echo 5969 >tasks # echo 20000 >cpu.cfs_quota_us # 設置可使用的cpu時間為20ms # pidstat -p 5969 1 Linux 3.10.0-1062.9.1.el7.x86_64 (test-prd-10-47-4-40.gzyq.ts.lan) 11/23/2020 _x86_64_ (4 CPU) 03:24:48 PM UID PID %usr %system %guest %CPU CPU Command 03:24:49 PM 0 5969 20.00 0.00 0.00 20.00 3 bash 03:24:50 PM 0 5969 20.00 0.00 0.00 20.00 3 bash 03:24:51 PM 0 5969 20.00 0.00 0.00 20.00 3 bash