####################################### accurate_sleep.py ##################################
# Halverson 5/24/2015
# This is a better sleep function.  It will now fall behind due to cpu time used in the
# calling program.
# The accuracy is "long-run."  It is not any more accurate in terms of single sleep times.


# Examples from http://www.cyberciti.biz/faq/howto-get-current-date-time-in-python/


import time,math

accurate_sleep_start_time=None

def accurate_sleep(secs_to_sleep):
  global accumulated_secs_to_sleep
  global accurate_sleep_start_time
  if accurate_sleep_start_time==None:
    print "Initializing accurate_sleep"
    #accurate_sleep_start_time=math.floor(time.time())    #Make the starting reference time
    accurate_sleep_start_time=time.time()       #Make the starting reference time
    #  Take out the "floor" if you don't like the starting time truncated to the second.
    accumulated_secs_to_sleep=0.0
  accumulated_secs_to_sleep = accumulated_secs_to_sleep + secs_to_sleep
  sleep_time=(accumulated_secs_to_sleep+accurate_sleep_start_time) - time.time()
  #print "sleep_time=",sleep_time
  if sleep_time > 0.0:
    time.sleep(sleep_time)
  return()

#Test program
#from datetime import datetime
#T=input("How many seconds between each measurement? ")
#while True:
#  accurate_sleep(T)
#  print "current date and time is", datetime.now()
  