Search code examples
pythontimeprecisionsleep

How to make a delay at ~100-200us


I would like to try some hardware testing with python. I have to send commands to the hardware where there is a specification for consecutive bytes transmission time interval (~100-200us). However, I found the sleep() method in time module unstable when the delay time is too small. Is there any way/operations that takes ~100-200us?

I also wonder what is the accuracy of the function time(), can it really time a 100us interval?

from time import time, sleep
a = []
start = time()
for i in range(10):
    sleep(200e-6)
    a.append(time()-start)

this is what 'a' looks like:

[0.0010325908660888672,
 0.004021644592285156,
 0.006222248077392578,
 0.008239507675170898,
 0.009252071380615234,
 0.01157999038696289,
 0.013728857040405273,
 0.014998674392700195,
 0.016725540161132812,
 0.0187227725982666]

Solution

  • About accuracy of time.sleep

    It looks like time.sleep() only has millisecond resolution. Though it could range between a few milliseconds to over 20 milliseconds (best case scenarios), based on what OS you are using, it does not look like you will get accurate microsecond sleep execution from it.

    References

    1. Must See This: How accurate is python's time.sleep()?
    2. usleep in Python
    3. https://github.com/JuliaLang/julia/issues/12770
    4. https://gist.github.com/ufechner7/1aa3e96a8a5972864cec

    Another Option:

    You could potentially then look for creating a C/C++ wrapper around the timer-code to use it from Python.