Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reducing the CPU usage of a thread or process

There a bunch of other questions like this, but the only substantial answer I've seen is the one where you use SetPriorityClass to give priority to other processes. This is not what I want. I want to explicitly limit the CPU usage of my thread/process.

How can I do this?

Edit: I can't improve the efficiency of the process itself, because I'm not controlling it. I'm injecting my code into a game which I'd like to 'automate' in the background.


1 Answers

The best solution to limiting the cpu usage for a process or thread is to make sure that the thread or process uses less cpu.

That can best be done by improving the efficiency of the code, or by calling it less often. The aim is to make sure that the process doesn't continually consume all of its available time slice.

Things to try:

  1. Work out what is actually taking up all of the CPU. Optimize heavy processing areas - ideally with a change of algorithm.
  2. Minimise polling wherever possible.
  3. Try to rely on the operating system's ability to wake your process when necessary. eg. By waiting on files/sockets/fifos/mutexes/semaphores/message queue etc.
  4. Have processes self regulate their processor usage. If your process is doing a lot of work in an endless loop insert a sched_yield() or sleep() after every N loops. If there are no other processes waiting for CPU usage then your process will get rescheduled almost immediately, but will allow the rest of the system to use cpu time when necessary.
  5. Rearrange your processing to allow lower priority activities to be run when your process is at idle.
  6. Carefully adjust thread or process priorities. But be aware, as @Mooing Duck has said, that by doing this you may just shift the CPU usage from one place to a different place without seeing an overall improvement.
like image 185
Andrew Edgecombe Avatar answered Feb 09 '26 14:02

Andrew Edgecombe