准确时间<10ms时调用代码

2024-04-20 11:43:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我从这里开始:https://stackoverflow.com/questions/12435211/python-threading-timer-repeat-function-every-n-seconds#=

我想发送MIDI时间码,跨平台。我检查了从我的代码中记录的输入,时间在这里或那里损失了100毫秒左右,这还不够准确-我需要每秒发送96-120次,间隔均匀的消息。我从Cubase得到的输入在这方面非常非常准确(10秒后最多关闭1毫秒),但是我感觉(我希望)我还没有找到用Python实现它的最佳方法。另外,我希望时间安排不受通话间隔处理量的影响,我猜这取决于在任何给定时刻有多少音乐活动发生。但这只是时间码,没有注释,即使这样,时间也不够准确。 我在Windows7(稍后在OSX10.9和Linux上)上使用Python2.7。 无论我在哪里寻找,我都能找到对代码或函数进行基准测试的结果,但我想要的是每秒执行100多次代码而不会出现漂移。有什么想法吗? 我的代码:

import time
import threading as th

ind = 0

class MyThread(th.Thread):
    def __init__(self, event):
        th.Thread.__init__(self)
        self.stopped = event
        self.ind = 0

    def run(self):
        while not self.stopped.wait(0.01):
            self.ind += 1
            if self.ind % 100 == 0:
                print time.clock()
            if self.ind == 1000:
                self.stopped.set()

stopFlag = th.Event()
thread = MyThread(stopFlag)
thread.start()

万分感谢! -查克


Tags: 代码importself间隔timeinitdef时间
1条回答
网友
1楼 · 发布于 2024-04-20 11:43:57

如果你想精度低于10毫秒,你需要在一个实时系统中编程,比如微处理器。Windows7由于中断而不够精确。据我所知,Windows最多16毫秒。你知道吗

相关问题 更多 >