title: C++ While loop, usleep()/sleep() how not to use 90% of CPU? (Ubuntu 12.04)
body: <p>Suppose I have C++ code such as</p>
  
  <pre><code>#include "myheaderfiles.h"
  //..some stuff
  //...some more stuff
  int main()
  {
     double milliseconds;
     int seconds;
     int minutes;
     int timelimit=2;
     ...
     ...
     //...code here that increments 
     //.....milliseconds,seconds, and minutes
  
     while(minutes &lt;=timelimit)
     {
        //...do stuff
        if(milliseconds&gt;500)
        {
           //...do stuff 
           //...every half second
        } //end if
     } //end while
  }//end main
  </code></pre>
  
  <p>The program will run fine and does what its supposed to do but it will use up 90%+ of my cpu. </p>
  
  <p>It was suggested to me to use usleep() in my while loop ever 100ms or so since I really only care about doing stuff every 500ms anyway. That way, it hog the CPU when its not needed.</p>
  
  <p>So I added it to my while loop like so</p>
  
  <pre><code>   while(minutes &lt;=timelimit)
     {
        //...do stuff
        if(milliseconds&gt;500)
        {
           //...do stuff 
           //...every half second
        } //end if
        usleep(100000);
     } //end while
  </code></pre>
  
  <p>It compiles fine, but when I run it, the program will hang right at usleep and never return. I read somewhere that before calling usleep, one needs to flush all buffers, so I flushed all file streams and couts etc etc. Still no luck.</p>
  
  <p>I've searched for 2 days for a solution. I've used sleep() too, with no luck. </p>
  
  <p>I found a few alternatives but they seem complicated and will add a lot of code to my program that I dont really fully understand which will complicate it and make it messy, plus it might not work. </p>
  
  <p>I never really put too much thought in my while() loops before because most of the programs I wrote were for microcontrollers or FPGAs which is no problem to hog the processor.</p>
  
  <p>If anyone can help.... any resources, links,books? Thanks.</p>