cuylimit.lua: limit CPU usage of a multi-proccess program

Words
146
Reading
1 min
Listen
Play
9y

I love to have fast applications, but when they use too much CPU... things get really hot!

laptop-on-fire.jpeg
Source: Pixabay

For example, Chrome outperforms all web browsers because of its speed, yet it eats computing resources! That is something I can't afford to happen since I need to use my laptop for several other tasks than browsing. Also, I don't like how it feels when my laptop is so warm!

Time to cool things down!

My first (failed) attempt was to run cpulimit for each of my heavy desktop apps:

$ cpulimit -l 40 firefox
$ cpulimit -l 40 chromium-browser

(Yeah, I use firefox as well :P)

Unfortunately things stayed warm when Chrome was running. Hence cpulimit reportedly controls the CPU usage of a given process name:

$ cpulimit -l 50 -e chromium-browser
Process 3251 detected

It was really frustrating to be honest... So I tried other stuff: cgroup... but it has not worked that well. There seems to be some regression bug that keeps cgroup far from desktop distributions.

The problem

Then I tried to give cpulimit a second chance. With the help of my friend htop command I noticed that Chrome likes to create and destroy processes very often. The limitation of cpulimit is that it can only handle one process at a time. Multi-process applications are beyond its powers.

Lua to the rescue!

My new Lua script monitors for a given pattern every second, grabs each process id (pid) that matches such pattern and then starts a cpulimit instance for each matching process.

The command cpulimit has two helpful options. The first one is -z which instructs to cpulimit finish when there is not process found or when such process dies. The other option is -b, allowing to run cpulimit in the background. Both options make things way easier.

This is how to run cuylimit.lua:

$ cuylimit.lua chromium 50

output-htop.png
Seen column CPU%? The Chrome beast is under control!

Don't run away that fast!

If you liked this stuff please vote @dropahead for witness!

Talk is cheap, code is gold! You had better start a pull request if you want to say something about my precious code. Here: https://github.com/develCuy/cuylimit

Happy hacking and keep steeming hard!

cuylimit.lua: limit CPU usage of a multi-proccess program | Ecency