提高小等待值的 asyncio.sleep(wait) 性能 (< 10ms)

问题描述 投票:0回答:1

我正在使用 Raspi 通过

python-osc
服务器控制步进电机,通过
await asyncio.sleep(wait_in_s)
在异步过程中产生触发信号。

我发现,与阻塞

asyncio.sleep
函数相比,非阻塞
time.sleep()
例程在频率高于 100Hz 时表现出非常差的性能,因为它产生离散的步骤。

Asyncio.sleep()
:命令与测量的睡眠时间:

Asyncio.sleep(): Commanded vs. measured sleep time

time.sleep()
:命令与测量的睡眠时间:

time.sleep():  Commanded vs. measured sleep time

是否可以使用其他性能更好的异步协程,或者以异步方式使用

time.sleep()
函数?

我无法使用硬件 pwm 控制器,因为我必须计算脉冲数才能将步进电机停止在特定角度,并提高/降低速度。

asyncio.sleep() 的测试平台:


import time
import asyncio
import numpy as np

from matplotlib import pyplot as plt

async def main(frequency):
    time_last = time.time()
    x_end = 3
    sleep_meas = 0
    await asyncio.sleep(1 / (frequency))
    await asyncio.sleep(1 / (frequency))
    await asyncio.sleep(1 / (frequency))
    sleep_meas = time.time() - time_last
    print(f"{frequency}: {1/(sleep_meas/x_end)}")
    return 1/(sleep_meas/x_end)

f = np.geomspace(10, 5000, 1000)

f_meas = []
for freq in f:
    f_meas.append(asyncio.run(main(freq)))

fig, ax = plt.subplots()
ax.plot(f, f_meas)
ax.set_xlabel("commanded frequency")
ax.set_ylabel("measured frequency")

plt.savefig("test3.png")
plt.show()

python raspberry-pi python-asyncio
1个回答
0
投票

time.sleep
不是异步的,所以它对你来说没用。

我得到的最好的建议是

asyncio.sleep(0)
实际上并不睡眠,它只是将你排在队列的末尾,所以如果你计算什么时候你想完成等待,并且只是使用
asyncio.sleep(0)
循环,直到达到该时间为止,这是您在仍然使用异步功能的情况下可能获得的最低延迟。如果这不起作用,则可能意味着您的其他任务正在垄断事件循环,而不是
asyncio.sleep
延迟的固有问题。

© www.soinside.com 2019 - 2024. All rights reserved.