以恒定速率循环以高精度进行信号采样 [英] Looping at a constant rate with high precision for signal sampling

查看:35
本文介绍了以恒定速率循环以高精度进行信号采样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Python 中以 10Khz 的频率对信号进行采样.尝试运行此代码时没有问题(1KHz):

I am trying to sample a signal at 10Khz in Python. There is no problem when try to run this code(at 1KHz):

import sched, time

i = 0
def f(): # sampling function
    s.enter(0.001, 1, f, ())
    global i
    i += 1
    if i == 1000:
        i = 0
        print "one second"

s = sched.scheduler(time.time, time.sleep)

s.enter(0.001, 1, f, ())
s.run()

当我尝试缩短时间时,它开始超过一秒(在我的计算机中,10e-6 时为 1.66 秒).是否可以在 Python 中以特定频率运行采样函数?

When I try to make the time less, it starts to exceed one second(in my computer, 1.66s at 10e-6). It it possible to run a sampling function at a specific frequency in Python?

推荐答案

您没有考虑代码的开销.每次迭代,这个错误都会累加并扭曲时钟".

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

我建议使用带有 time.sleep() 的循环(参见对 https 的评论)://stackoverflow.com/a/14813874/648265) 并从下一个参考时刻开始计算睡眠时间,这样不可避免的错误就不会加起来:

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).

这篇关于以恒定速率循环以高精度进行信号采样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆