Python service uses 100% of CPU on while loop with sleep (inside docker container)

  async-await, asynchronous, docker, python, sleep

I have a python3 code that does something like this:

import asyncio
import time

async def main():
    while True:
        if should_end():
            break
        # time.sleep(0.5)
        await asyncio.sleep(0.5)

if __name__ == "__main__":
    asyncio.run(main())

I’ve tested it with time.sleep(0.5) and await asyncio.sleep(0.5) but for both cases it is using 100% of CPU.

CONTAINER ID        NAME                CPU %               MEM USAGE / LIMIT     MEM %               NET I/O             BLOCK I/O           PIDS
f698d943d5d5        my-container      100.66%                 5.7MiB / 15.52GiB   0.16%               0B / 0B             56.9MB / 0B         30

Source: Docker Questions

LEAVE A COMMENT