简体   繁体   English

在python 2中每n毫秒在python中定期执行一个函数

[英]Execute a function periodically in python for every n milliseconds in python 2

I'm wondering how to execute a function in Python for every 10ms.我想知道如何在 Python 中每 10 毫秒执行一次函数。 I tried with threading (using threading.Timer(0.001, fun) ), but threading.Timer executes properly only up to seconds.我尝试使用线程(使用threading.Timer(0.001, fun) ),但threading.Timer最多只能正确执行几秒钟。 Is there any to execute a task/function in ms(milli seconds)?有没有在毫秒(毫秒)内执行任务/功能?

The code is as follows.代码如下。

def task():
    print "called every 10ms"
    print time.ctime()
    threading.Timer(0.01,task).start()

task()

I tried it on my own and it works, but it seems that Python isn't that fast in the console.我自己尝试过,它可以工作,但似乎 Python 在控制台中并没有那么快。 In my case it just gets to about 60 runs per second.在我的情况下,它每秒运行大约 60 次。

import threading
import time

def hello(*args):
    print(str(args[0])+" It's "+str(time.ctime()))
    next=int(args[0])+1
    threading.Timer(0.001, hello,[str(next)]).start()

hello("1")

I also had a similar problem in which I needed to do some sampling at 1000Hz and that couldn't have any considerable drift on the long run.我也有一个类似的问题,我需要在 1000Hz 下进行一些采样,并且从长远来看不会有任何明显的漂移。 Trying to sleep 0.001 seconds would always result in a lower sampling rate (drifting), even when I tried to estimate the time the sampling code took to execute (with a time.time() after and before sleeping).尝试休眠 0.001 秒总是会导致较低的采样率(漂移),即使我试图估计采样代码执行所需的时间(在休眠之后和之前使用 time.time())。

It turns out that a simple solution is to keep track of the number of executions and use it to calculate if you are late or not.事实证明,一个简单的解决方案是跟踪执行次数并使用它来计算您是否迟到。

import time
import threading

class PeriodicSleeper(threading.Thread):
    def __init__(self, task_function, period):
        super().__init__()
        self.task_function = task_function
        self.period = period
        self.i = 0
        self.t0 = time.time()
        self.start()

    def sleep(self):
        self.i += 1
        delta = self.t0 + self.period * self.i - time.time()
        if delta > 0:
            time.sleep(delta)
    
    def run(self):
        while True:
            self.task_function()
            self.sleep()

And for testing:并用于测试:

def task():
    t = time.time()
    if abs(t - round(t)) <= 0.0005:
        print(t, 'Mean Frequency:', sleeper.i / (t - sleeper.t0))

sleeper = PeriodicSleeper(task, 0.001)

Resulting in a deviation that is less than half a period and a mean frequency that converges to the desired value.导致小于半个周期的偏差和收敛到所需值的平均频率。

1623373581.0000355 Mean Frequency: 999.8594124106243
1623373582.0000308 Mean Frequency: 999.9576212826602
1623373583.0000248 Mean Frequency: 999.9771123402633
1623373584.0000222 Mean Frequency: 999.9844427446347
1623373585.0000298 Mean Frequency: 999.9862123585227
1623373586.000023 Mean Frequency: 999.989990000442
....
1623373863.0000231 Mean Frequency: 999.9998049640523
1623373864.000024 Mean Frequency: 999.9998022878916
1623373865.0000224 Mean Frequency: 999.9998088494829
1623373866.0000248 Mean Frequency: 999.9998011675633

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM