Swind D.C. Xu
Swind D.C. Xu

Reputation: 225

How to limit the CPU usage of process?

I want to limit the CPU usage of process in a GPU Server. I find some ways, "nice" or "cpulimit". But they are not exactly what I want.
cpulimit allow a process to run as fast as it wants until it has exceeded a percentage after which it gets a SIGSTOP, followed by a sleep, and a SIGCONT.
But I don't want the process which exceeded a percentage to sleep. I just hope that it does not exceed a certain percentage. And keep it running in a normal way.

For example, when I run cpulimit -p 1111 -l 30, the terminal will be
[1]+ Stopped
This is not what I want.

Upvotes: 5

Views: 3098

Answers (2)

A possible way might be to design your own "shell-like" program which runs another process (or process group) and send it alternatively the SIGSTOP and SIGCONT signals (see signal(7) for more). For example, if you want some program to use no more than 50% of the cpu time, you might start it, let it run for 10 milliseconds, send it a SIGSTOP, sleep for 10 milliseconds, send it a SIGCONT, sleep for 10 milliseconds, send it a SIGSTOP and so forth.

A proof-of-concept of such a controlling program is my half.c utility (GPLv2+ licensed). BTW it does not show Stopped on the terminal (a message shown by your shell), because that half program does not stop itself (only some child process).

FWIW, I developed that program more than ten years ago, to be able to compile the Linux kernel on some overheating MSI S270 laptop

(the actual story is slightly more complex, and also involved too cheap RAM modules, which, when heated too much, worked wrong; I needed more than a year to realize that changing the RAM modules solved the overall hardware problem).

Upvotes: 2

Alexis Tacnet
Alexis Tacnet

Reputation: 535

I don't think this is possible without sending a sleep to your program. But I don't think you should be worried about sleeps, because this is what UNIX does when another thread requests an access to the CPU.

If you see that you program is using 50% of a CPU core, it is 50% of the time, because a CPU core can only do one or two threads at a time (depending of your configuration, lscpu to see on linux).

If you're building a app that consume always 100% of a core and never let a other process enter in, it may be possible, but you never know if your kernel will one time allow some CPU to another emergency program.

So my advice is to consider the fact that your app may be paused, because it may happen, and it is something you need obviously.

Hope I help you :) See ya !

Upvotes: 3

Related Questions