我正在使用一个答案中的do_every()以一定的速率(每秒500000)执行一个函数(下面的链接)。但是,我需要添加一项功能,以便能够根据按键更改时间段。虽然我通过不断检查mscvrt.khbit()设法实现了这一目标,但它却极大地降低了功能的性能。
代码:
def do_every(period,f,*args):
def g_tick():
t = time.time()
count = 0
while True:
#this continuous if check is degrading performance
if msvcrt.kbhit():
#change period value here based on the key pressed
count += 1
yield max(t + count*period - time.time(),0)
time.sleep(period)
g = g_tick()
while True:
time.sleep(g.next())
f(*args)
是否还有其他方法不会影响性能?每次都重新初始化内部g_tick(),并使用period作为全局变量可以解决问题,但是我主要关心的是函数性能。
链接到从do_every()被选择的地方得到的答案: Executing periodic actions in Python