Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

python - Looping at a constant rate with high precision for signal sampling

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...