#!/usr/bin/python

from datetime import datetime
from math import sqrt

import time

WAIT_TIME = 0.050
ITERATIONS = 100

# Copied from http://www.physics.rutgers.edu/~masud/computing/WPark_recipes_in_python.html

def meanstdv(x):
  n, mean, std = len(x), 0, 0
  for a in x:
    mean = mean + a
  mean = mean / float(n)

  for a in x:
    std = std + (a - mean)**2
  std = sqrt(std / float(n-1))

  return mean, std

# Copied from http://stackoverflow.com/questions/1133857/how-accurate-is-pythons-time-sleep

def sleepError(amount=WAIT_TIME):
  start = datetime.now()
  time.sleep(amount)
  end = datetime.now()
  delta = end - start
  return abs((delta.seconds + delta.microseconds / 1000000.) - amount)

errors = [1000. * sleepError() for i in xrange(ITERATIONS)]
print 'Error: average %0.2fms; std dev %0.2fms' % meanstdv(errors)

@@ -16,22 +16,8 @@
 on%0A%0A
-from datetime 
 impo
@@ -32,26 +32,28 @@
 ime%0A
-from
+import
  math
- 
+%0A
 import s
 qrt%0A
@@ -52,12 +52,10 @@
 rt s
-qrt%0A
+ys
 %0Aimp
@@ -79,17 +79,29 @@
 ME = 0.0
-5
+05%0APRESKIP = 
 0%0AITERAT
@@ -109,17 +109,51 @@
 ONS = 10
-0
+%0AMICROSECONDS_PER_SECOND = 1000000.
 %0A%0A# Copi
@@ -397,16 +397,21 @@
   std = 
+math.
 sqrt(std
@@ -450,132 +450,27 @@
 td%0A%0A
-# Copied from http://stackoverflow.com/questions/1133857/how-accurate-is-pythons-time-sleep%0A%0Adef sleepError(amount=WAIT_TIME
+def sleepError(wait
 ):%0A 
@@ -478,16 +478,25 @@
 start = 
+datetime.
 datetime
@@ -515,21 +515,19 @@
 e.sleep(
-amoun
+wai
 t)%0A  end
@@ -529,16 +529,25 @@
   end = 
+datetime.
 datetime
@@ -581,19 +581,16 @@
 t%0A  
-return abs(
+error = 
 (del
@@ -627,44 +627,228 @@
 s / 
-1000000.) - amount)%0A%0Aerrors = %5B1000.
+MICROSECONDS_PER_SECOND) - wait%0A  if error %3C 0:%0A    print 'UNDERRUN:', error  # Never happens.%0A    error = -error%0A%0A  return error%0A%0Adef getSleepErrors(iterations=ITERATIONS, t=WAIT_TIME):%0A  return %5BMICROSECONDS_PER_SECOND
  * s
@@ -857,16 +857,17 @@
 epError(
+t
 ) for i 
@@ -880,34 +880,178 @@
 nge(
-ITERATIONS)%5D%0Aprint 'Error:
+iterations)%5D%0A%0Adef reportSleepErrors(errors, iterations=ITERATIONS, t=WAIT_TIME):%0A  print '%25d iterations, wait %25dus' %25 (iterations, t * MICROSECONDS_PER_SECOND)%0A  print ' 
  ave
@@ -1056,21 +1056,18 @@
 verage %25
-0.2fm
+du
 s; std d
@@ -1074,31 +1074,454 @@
 ev %25
-0.2fms' %25 meanstdv(errors
+dus' %25 meanstdv(errors)%0A  print '  min: %25dus, max: %25dus' %25 (min(errors), max(errors))%0A%0Adef runSleepReport(iterations=ITERATIONS, wait=WAIT_TIME):%0A  wait = float(wait)%0A  iterations = int(iterations)%0A  if PRESKIP:%0A    # Skipping the first few to get stability seems to have no effect.%0A    getSleepErrors(PRESKIP, wait)%0A%0A  reportSleepErrors(getSleepErrors(iterations, wait), iterations, wait)%0A%0Aif __name__ == '__main__':%0A  runSleepReport(*sys.argv%5B1:%5D
 )%0A

Add TestSleepAccuracy.py