Reducing CPU usage by a thread or process

There are tons of other questions out there, but the only significant answer I've seen is 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 cannot improve the efficiency of the process itself, because I have no control over it. I was injecting my code into a game that I would like to "automate" in the background.


source to share

4 answers

How about issuing a sleep command at regular intervals?



The best solution to limit CPU usage for a process or thread is to make sure the thread or process uses fewer CPUs.

This is best done by improving the efficiency of the code or by calling it less frequently. The goal is to ensure that the process does not constantly consume the entire available time slice.

Things to Try:

  • Design something that actually takes up the entire processor. Optimize areas of large processing - ideally with an algorithm change.
  • Keep polling to a minimum where possible.
  • Try to rely on the operating system's ability to wake up your process when needed. eg. Expecting files / sockets / fifos / mutexes / semaphores / message queue, etc.
  • Processes self-regulate the use of processors. If your process runs a lot in an infinite loop, insert sched_yield () or sleep () after every N cycles. If there are no other processes waiting for CPU usage, your process will be ported almost immediately, but will allow the rest of the system to use CPU time when needed.
  • Change the processing order to allow lower priority actions to be performed when your process is idle.
  • Adjust the priorities of threads or processes carefully. But keep in mind, as @Mooing Duck said, that by doing this, you can simply switch CPU usage from one place to another without seeing an overall improvement.


Your question is broad - I don't know what it does. You can, of course, monitor the I / O stream and force it to abandon the processor after passing a certain threshold.



I ended up listing the thread list and then setting a 100ms timer that paused the thread list two out of every five iterations (which theoretically reduces CPU consumption by 40%).

Thanks for all the answers.



All Articles