Looping at a constant rate with high precision for signal sampling

旧时模样 提交于 2019-11-28 02:20:56
ivan_pozdeev

You didn't account for the code's overhead. Each iteration, this error adds up and skews the "clock".

I'd suggest to use a loop with time.sleep() instead (see comments to https://stackoverflow.com/a/14813874/648265) and count the time to sleep from the next reference moment so the inevitable error doesn't add up:

period=0.001
t=time.time()
while True:
    t+=period
    <...>
    time.sleep(max(0,t-time.time()))     #max is needed in Windows due to
                                         #sleep's behaviour with negative argument

Note that the OS scheduling will not allow you to reach precisions beyond a certain level since other processes have to preempt yours from time to time. In this case, you'll need to use some OS-specific facilities for multimedia applications or work out a solution that doesn't need this level of accuracy (e.g. sample the signal with a specialized app and work with its saved output).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!