Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How limit cpu usage from specific process?

How i can limit cpu usage to 10% for example for specific process in windows C++?

like image 736
lebron2323 Avatar asked Dec 22 '25 07:12

lebron2323


2 Answers

You could use Sleep(x) - will slow down your program execution but it will free up CPU cycles
Where x is the time in milliseconds

like image 193
tom502 Avatar answered Dec 23 '25 20:12

tom502


This is rarely needed and maybe thread priorities are better solution but since you asked, what you should is:

  1. do a small fraction of your "solid" work i.e. calculations
  2. measure how much time step 1) took, let's say it's twork milliseconds
  3. Sleep() for (100/percent - 1)*twork milliseconds where percent is your desired load
  4. go back to 1.

In order for this to work well, you have to be really careful in selecting how big a "fraction" of a calculation is and some tasks are hard to split up. A single fraction should take somewhere between 40 and 250 milliseconds or so, if it takes less, the overhead from sleeping and measuring might become significant, if it's more, the illusion of using 10% CPU will disappear and it will seem like your thread is oscillating between 0 and 100% CPU (which is what happens anyway, but if you do it fast enough then it looks like you only take whatever percent). Two additional things to note: first, as mentioned before me, this is on a thread level and not process level; second, your work must be real CPU work, disk/device/network I/O usually involves a lot of waiting and doesn't take as much CPU.

like image 21
sbk Avatar answered Dec 23 '25 20:12

sbk