title: How do I ensure that a Python while-loop takes a particular amount of time to run?
body: <p>I'm reading serial data with a while loop. However, I have no control over the sample rate.</p>
  
  <p>The code itself seems to take 0.2s to run, so I know I won't be able to go any faster than that. But I would like to be able to control precisely how much slower I sample.</p>
  
  <p>I feel like I could do it using 'sleep', but the problem is that there is potential that at different points the loop itself will take longer to read(depending on precisely what is being transmitted over serial data), so the code would have to make up the balance.</p>
  
  <p>For example, let's say I want to sample every 1s, and the loop takes anywhere from 0.2s to 0.3s to run. My code needs to be smart enough to sleep for 0.8s (if the loop takes 0.2s) or 0.7s (if the loop takes 0.3s).</p>
  
  <pre><code>import serial
  import csv
  import time
  
  #open serial stream
      while True:
  
          #read and print a line
          sample_value=ser.readline()
          sample_time=time.time()-zero
          sample_line=str(sample_time)+','+str(sample_value)
          outfile.write(sample_line)
          print 'time: ',sample_time,', value: ',sample_value
  </code></pre>