How to limit resource usage for a given process?
I have a process for an application which needs to run, but ends up using far too much IO usage for what it does. And really crashes my computer, making it impossible to do anything else whilst it is running.
So I was wondering if there is a way to limit IO usage, RAM and CPU for a given process? And its sub-processes of course.
This is on my Ubuntu 18.04 LTS system.
Solution 1:
You should use a combination of all cgexec
, cpulimit
and ionice
:
-
Limit RAM and SWAP:
sudo cgcreate -g memory:/szMyGroup echo $(( 512 * 1024 * 1024 )) | sudo tee /sys/fs/cgroup/memory/szMyGroup/memory.limit_in_bytes echo $(( 1024 * 1024 * 1024 )) | sudo tee /sys/fs/cgroup/memory/szMyGroup/memory.memsw.limit_in_bytes
The above commands create a control group named
szMyGroup
(E.g. in your casegroup-great-uncle
), set a cap to the processes run underszMyGroup
up to 512 MB of physical memory and up to 1024 MB of swap and then:sudo cgexec -g memory:szMyGroup szMyProgram
which will run your program under the
szMyGroup
control group, thus ensuring they adhere to the limits -
limit the disk IO:
sudo ionice --class 3 --pid $(pgrep -f szMyProgram)
The above command uses
pgrep
with reusing parts of the current command-line to limit its disk access to only use the disk when no other program is using it -
Limit the CPU:
sudo cpulimit --limit=25 --pid=!#:4
The program's CPU is now limited to 25% of maximum
If the program does not use a lot of CPU to begin with, lower the value of cpulimit to half or less of what it currently uses.