Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use less CPU with loops?

I've got a loop that looks like this:


while (elapsedTime < refreshRate) 
{
    timer.stopTimer();
    elapsedTime=timer.getElapsedTime();
}
I read something similar to this elsewhere (C Main Loop without 100% cpu), but this loop is running a high resolution timer that must be accurate. So how am I supposed to not take up 100% CPU while still keeping it high resolution?
like image 939
Mark Avatar asked Jul 19 '10 22:07

Mark


People also ask

Does while loop consume CPU?

It consumes all CPU it can get, unless... The loop body is trivial, and optimised away. The loop contains a blocking operation (like a file or network operation). The link you provide suggests to avoid this, but it is often a good idea to block until something relevant happens.

How do I force a program to use less CPU?

If your processor has two cores or more you can go to task manager and go to processes and right click on the program name and click Set affinity and set the program to use fewer cores. It will then take longer to do the actions you're asking but will cause a SIGNIFICANT decrease in CPU usage.


1 Answers

You shouldn't busy-wait but rather have the OS tell you when the time has passed.

http://msdn.microsoft.com/en-us/library/ms712704(VS.85).aspx

High resolution timers (Higher than 10 ms)

http://msdn.microsoft.com/en-us/magazine/cc163996.aspx

like image 102
tovare Avatar answered Oct 29 '22 00:10

tovare