To be this exact you probably need to use cgroups.
Here is a quick example I tested on Ubuntu 20.04. For simplicity, this is a single cpu VM and all commands were run as root.
apt-get install cgroup-tools stress
- create a hierarchy of cgroups that will be cpu limited. The parent is named
max80
and it has A
and B
beneath it.
cgcreate -g cpu:max80/A -g cpu:max80/B
- limit the parent cgroup
max80
to 80% of the CPU.
echo 1000000 > /sys/fs/cgroup/cpu/max80/cpu.cfs_period_us
echo 800000 > /sys/fs/cgroup/cpu/max80/cpu.cfs_quota_us
- limit the child cgroup
B
to have 10% of shares. You mentioned 1% in your post, but 10% is easier to show. B
will use all the available CPU, but if there is contention with processes in A
then it will be limited to 10%.
echo $((1024 * 10 / 100 )) > /sys/fs/cgroup/cpu/max80/B/cpu.shares
In action
- run a
stress
process in just A
. The CPU usage will be 80% for the stress
process doing the work.
root@ubuntu:~# cgexec -g cpu:max80/A stress --cpu 1 &
[1] 2040
stress: info: [2040] dispatching hogs: 1 cpu, 0 io, 0 vm, 0 hdd
root@ubuntu:~# ps -o pid,%cpu,cmd --sort -%cpu -p $(pidof stress)
PID %CPU CMD
2041 80.4 stress --cpu 1
2040 0.0 stress --cpu 1
root@ubuntu:~# killall stress
- run a
stress
process in just B
. The CPU usage will be 80%.
root@ubuntu:~# cgexec -g cpu:max80/B stress --cpu 1 &
[1] 2065
stress: info: [2065] dispatching hogs: 1 cpu, 0 io, 0 vm, 0 hdd
root@ubuntu:~# ps -o pid,%cpu,cmd --sort -%cpu -p $(pidof stress)
PID %CPU CMD
2066 80.6 stress --cpu 1
2065 0.0 stress --cpu 1
root@ubuntu:~# killall stress
- run a
stress
process in A
and B
. The CPU usage will be split 90%/10%.
root@ubuntu:~# cgexec -g cpu:max80/A stress --cpu 1 &
[1] 2078
stress: info: [2078] dispatching hogs: 1 cpu, 0 io, 0 vm, 0 hdd
root@ubuntu:~# cgexec -g cpu:max80/B stress --cpu 1 &
[2] 2080
stress: info: [2080] dispatching hogs: 1 cpu, 0 io, 0 vm, 0 hdd
root@ubuntu:~# ps -o pid,%cpu,cmd --sort -%cpu -p $(pidof stress)
PID %CPU CMD
2079 71.9 stress --cpu 1
2081 7.2 stress --cpu 1
2078 0.0 stress --cpu 1
2080 0.0 stress --cpu 1
root@ubuntu:~# killall stress
Links