Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 465
Mayan Avatar asked Nov 02 '25 14:11

Mayan


1 Answers

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:

  • Take a look at the high precision timers available from winmm.lib: Creating a High-Precision, High-Resolution, and Highly Reliable Timer, Utilising Minimal CPU Resources. This resource shares some code (C++ perhaps) to create a high precision timer (they claim a 5% error) and if the precision happens to be at the order of 1 microsecond, then you probably be okay with it.
  • Also see this: How to make thread sleep less than a millisecond on Windows.

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

like image 118
CypherX Avatar answered Nov 04 '25 04:11

CypherX