title: Run loop every millisecond with sleep_for
body: <p>I want to run a loop inside a thread that calculates some data every millisecond. But I am having trouble with the sleep function. It is sleeping much too long.</p>
  
  <p>I created a basic console application in visual studio:</p>
  
  <pre><code>#include &lt;windows.h&gt;
  #include &lt;iostream&gt;
  #include &lt;chrono&gt;
  #include &lt;thread&gt;
  
  using namespace std;
  typedef std::chrono::high_resolution_clock Clock;
  
  int _tmain(int argc, _TCHAR* argv[])
  {
      int iIdx = 0;
      bool bRun = true;
  
      auto aTimeStart = Clock::now();
  
      while (bRun){
          iIdx++;
          if (iIdx &gt;= 500) bRun = false;
  
          //Sleep(1);
          this_thread::sleep_for(chrono::microseconds(10));
      }
  
      printf("Duration: %i ms\n", chrono::duration_cast&lt;std::chrono::milliseconds&gt;(Clock::now() - aTimeStart).count());
  
      cin.get();
  
      return 0;
  }
  </code></pre>
  
  <p>This prints out: <strong>Duration: 5000 ms</strong>
  The same result is printed, when i use Sleep(1);</p>
  
  <p>I would expect the duration to be <strong>500 ms</strong>, and not 5000 ms. What am I doing wrong here?</p>
  
  <p><strong>Update:</strong></p>
  
  <hr>
  
  <p>I was using Visual Studio 2013. Now I have installed Visual Studio 2015, and its fine - prints out: Duration: 500 ms (sometimes its 527 ms).</p>
  
  <p>However, this sleep_for still isn't very accurate, so I will look out for other solutions.</p>