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:
def busy_wait(dt):
current_time = time.time()
while (time.time() < current_time+dt):
pass
and could get down to 0.0001 seconds before breaking 1% accuracy.
The main questions I have are:
- Why is the sleep function so inaccurate (possibly a C issue)? Will getting a better CPU with a higher clock speed change this?
- Why would anyone use sleep? The only advantage I see, power conservation, is limited to embedded systems, no?
- Would it be viable to compensate for sleep's inaccuracy with calibration? Like so:
def sleep(dt): sleep(calibration_function(dt))
As an aside, I read that sleep doesn't even function well with long wait times: Upper limit in Python time.sleep()? 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. Karl Voigtland mentions using ctypes' nanosleep, but I feel this is overkill and that time.sleep should do it's intended behavior.
time.sleep is a broken python feature? Or does nobody care about accurate time measurement enough?