title: Python time.sleep vs busy wait accuracy
body: <p>I was playing around with the time.sleep function from python's standard library and found it inadequate for sub-ms delays. From testing I found it to actually wait 1.1-1.2 ms for a 1ms wait. Implementing a busy wait got the accuracy to within 1%. I used:</p>
  
  <pre><code>def busy_wait(dt):   
      current_time = time.time()
      while (time.time() &lt; current_time+dt):
          pass
  </code></pre>
  
  <p>and could get down to 0.0001 seconds before breaking 1% accuracy.</p>
  
  <p>The main questions I have are:</p>
  
  <ul>
  <li>Why is the sleep function so inaccurate (possibly a C issue)? Will getting a better CPU with a higher clock speed change this?</li>
  <li>Why would anyone use sleep? The only advantage I see, power conservation, is limited to embedded systems, no?</li>
  <li>Would it be viable to compensate for sleep's inaccuracy with calibration? Like so:</li>
  </ul>
  
  <pre>
  def sleep(dt):
      sleep(calibration_function(dt))
  </pre>
  
  <p>As an aside, I read that sleep doesn't even function well with long wait times: <a href="https://stackoverflow.com/questions/1941177/upper-limit-in-python-time-sleep">Upper limit in Python time.sleep()?</a>
  I also read somewhere on SO of making a loop of shorter time intervals to increase precision, but that is useless when I want to delay 0.01 sec. <a href="https://stackoverflow.com/a/1212070/2534876">Karl Voigtland</a> mentions using ctypes' nanosleep, but I feel this is overkill and that time.sleep should do it's intended behavior.</p>
  
  <p>time.sleep is a broken python feature? Or does nobody care about accurate time measurement enough?</p>