use monotonic rather than sleep

This commit is contained in:
Will McGugan
2023-01-27 09:58:07 +01:00
parent 7097783414
commit ae73c4783f

View File

@@ -1,5 +1,5 @@
from asyncio import sleep from asyncio import sleep
from time import process_time, time from time import process_time, monotonic
SLEEP_GRANULARITY: float = 1 / 50 SLEEP_GRANULARITY: float = 1 / 50
SLEEP_IDLE: float = SLEEP_GRANULARITY / 2.0 SLEEP_IDLE: float = SLEEP_GRANULARITY / 2.0
@@ -14,13 +14,13 @@ async def wait_for_idle(
min_sleep: Minimum time to wait. Defaults to 1/50. min_sleep: Minimum time to wait. Defaults to 1/50.
max_sleep: Maximum time to wait. Defaults to 1. max_sleep: Maximum time to wait. Defaults to 1.
""" """
start_time = time() start_time = monotonic()
while True: while True:
cpu_time = process_time() cpu_time = process_time()
await sleep(SLEEP_GRANULARITY) await sleep(SLEEP_GRANULARITY)
cpu_elapsed = process_time() - cpu_time cpu_elapsed = process_time() - cpu_time
elapsed_time = time() - start_time elapsed_time = monotonic() - start_time
if elapsed_time >= max_sleep: if elapsed_time >= max_sleep:
break break
if elapsed_time > min_sleep and cpu_elapsed < SLEEP_IDLE: if elapsed_time > min_sleep and cpu_elapsed < SLEEP_IDLE: