简体   繁体   中英

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.

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.

如何定期发出睡眠命令?

Your question is broad -- I don't know what it's doing. You can certainly track the thread's I/O and force it to give up the cpu after a certain threshold is passed.

I ended up enumerating a list of threads, then having a 100ms timer that suspended the list of threads two out of every five iterations (which in theory reduces CPU usage by 40%).

Thanks for all the answers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM