title: Simulating CPU Load In C++
body: <p>I am currently writing an application in Windows using C++ and I would like to simulate CPU load.</p>
  
  <p>I have the following code:</p>
  
  <pre><code>void task1(void *param) { 
  
  unsigned elapsed =0;
  unsigned t0;
  
  while(1){
  
      if ((t0=clock())&gt;=50+elapsed){//if time elapsed is 50ms
  
          elapsed=t0;
          Sleep(50);
      }
    }
  }
  
  int main(){
  
  int ThreadNr;
  
  for(int i=0; i &lt; 4;i++){//for each core (i.e. 4 cores)
      _beginthread( task1, 0, &amp;ThreadNr );//create a new thread and run the "task1" function
  }
  
  while(1){}
  }
  </code></pre>
  
  <p>I wrote this code using the same methodology as in the answers given in this thread: <a href="https://stackoverflow.com/questions/2514544/simulate-steady-cpu-load-and-spikes">Simulate steady CPU load and spikes</a></p>
  
  <p>My questions are:</p>
  
  <ol>
  <li>Have I translated the C# code from the other post correctly over to C++?</li>
  <li>Will this code generate an average CPU load of 50% on a quad-core processor?</li>
  <li>How can I, within reasonable accuracy, find out the load percentage of the CPU? (is task manager my only option?)</li>
  </ol>
  
  <p><strong>EDIT:</strong> The reason I ask this question is that I want to eventually be able to generate CPU loads of 10,20,30,...,90% within a reasonable tolerance. This code seems to work well for to generate loads 70%&lt; but seems to be very inaccurate at any load below 70% (as measured by the task manager CPU load readings). </p>
  
  <p>Would anyone have any ideas as to how I could generate said loads but still be able to use my program on different computers (i.e. with different CPUs)?</p>