我正在使用python标准库中的time.sleep函数,发现它不适合亚毫秒延迟.从测试中我发现实际等待1到1毫秒等待1.1-1.2毫秒.实现忙碌等待使准确度达到1%以内.我用了:
def busy_wait(dt):
current_time = time.time()
while (time.time() < current_time+dt):
pass
Run Code Online (Sandbox Code Playgroud)
并且可以在降低1%准确度之前下降到0.0001秒.
我的主要问题是:
def sleep(dt):
sleep(calibration_function(dt))
顺便说一句,我读到睡眠甚至不能很长时间等待:Python time.sleep()的上限? 我也在某处读到了制作一个更短时间间隔的循环来提高精度,但是当我想延迟0.01秒时,这是没用的.Karl Voigtland提到使用ctypes的nanosleep,但我觉得这有点过分,而且time.sleep应该做它的预期行为.
time.sleep是一个破碎的python功能?或者没有人关心准确的时间测量吗?
我需要快速准确地从列表中发送重复消息.一个列表需要每100ms发送一次消息,窗口为+/- 10ms.我尝试使用下面的代码,但问题是计时器等待100毫秒,然后所有计算都需要完成,使计时器落在可接受的窗口之外.
简单地减少等待是一个混乱,不可靠的黑客.如果在循环期间编辑列表,则消息循环周围会有一个Lock.
关于如何让python在100ms左右发送消息的想法?谢谢
from threading import Timer
from threading import Lock
class RepeatingTimer(object):
def __init__(self,interval, function, *args, **kwargs):
super(RepeatingTimer, self).__init__()
self.args = args
self.kwargs = kwargs
self.function = function
self.interval = interval
self.start()
def start(self):
self.callback()
def stop(self):
self.interval = False
def callback(self):
if self.interval:
self.function(*self.args, **self.kwargs)
Timer(self.interval, self.callback, ).start()
def loop(messageList):
listLock.acquire()
for m in messageList:
writeFunction(m)
listLock.release()
MESSAGE_LIST = [] #Imagine this is populated with the messages
listLock = Lock()
rt = RepeatingTimer(0.1,loop,MESSAGE_LIST)
#Do other stuff after …Run Code Online (Sandbox Code Playgroud) 我将如何使用linux下的python(在单核Raspberry Pi上运行)实现毫秒精度的数组处理.
我正在尝试解析MIDI文件中的信息,该文件已被预处理到一个数组,其中每毫秒我检查数组是否在当前时间戳处有条目并触发某些功能(如果有).
目前我正在使用time.time()并使用繁忙的等待(如此处所述).这会占用所有CPU,因此我选择了更好的解决方案.
# iterate through all milliseconds
for current_ms in xrange(0, last+1):
start = time()
# check if events are to be processed
try:
events = allEvents[current_ms]
# iterate over all events for this millisecond
for event in events:
# check if event contains note information
if 'note' in event:
# check if mapping to pin exists
if event['note'] in mapping:
pin = mapping[event['note']]
# check if event contains on/off information
if 'mode' in event:
if …Run Code Online (Sandbox Code Playgroud) do_it我使用这种方法在未来的不同时间发起几十次(不到千次)调用:
import threading
timers = []
while True:
for i in range(20):
t = threading.Timer(i * 0.010, do_it, [i]) # I pass the parameter i to function do_it
t.start()
timers.append(t) # so that they can be cancelled if needed
wait_for_something_else() # this can last from 5 ms to 20 seconds
Run Code Online (Sandbox Code Playgroud)
每次调用的运行时间do_it都非常快(远小于 0.1 毫秒)并且是非阻塞的。我想避免为这样一个简单的任务产生数百个新线程。
我怎样才能只用一个额外的线程来处理所有do_it调用呢?
有没有一种简单的方法可以用Python来做到这一点,不需要第三方库,只有标准库?
我写了很多依赖于精确的周期性方法调用的代码.我一直在使用Python的futures库将调用提交到运行时的线程池,并在循环中的调用之间休眠:
executor = ThreadPoolExecutor(max_workers=cpu_count())
def remote_call():
# make a synchronous bunch of HTTP requests
def loop():
while True:
# do work here
executor.submit(remote_call)
time.sleep(60*5)
Run Code Online (Sandbox Code Playgroud)
但是,我注意到这个实现在长时间运行后引入了一些漂移(例如,我运行此代码大约10个小时,并注意到大约7秒的漂移).对于我的工作,我需要在确切的秒上运行,毫秒甚至更好.有些人指出我asyncio("火与忘记"python async/await),但我无法在Python 2.7中使用它.
我不是在寻找黑客.我真正想要的是类似于Go time.Tick或Netty的东西HashedWheelTimer.
我需要编写函数-
random_number(minimum,maximum)
Run Code Online (Sandbox Code Playgroud)
在不使用随机模块的情况下,我这样做:
import time
def random_number(minimum,maximum):
now = str(time.clock())
rnd = float(now[::-1][:3:])/1000
return minimum + rnd*(maximum-minimum)
Run Code Online (Sandbox Code Playgroud)
我不确定这是否可以..是否有已知的方法来解决这个问题?
python ×8
python-2.7 ×2
timer ×2
event-loop ×1
function ×1
go ×1
linux ×1
midi ×1
performance ×1
random ×1
raspberry-pi ×1
repeat ×1
sleep ×1
time ×1
wait ×1