Sobes.tech
Middle+

async def check_response(delay: int, message: str) -> None: timeout = httpx.Timeout(timeout=5) client = httpx.AsyncClient( base_url=BASE_URL, timeout=timeout, ) async with client: response = await client.get(url=f"/delay/{delay}") print(response.status_code, message) async def main() -> None: await check_response(delay=2, message="from first line"), await check_response(delay=2, message="from second line"), await check_response(delay=2, message="from third line"), if __name__ == "__main__": print("Total time:", timeit.timeit(lambda: asyncio.run(main()), number=2))

sobes.tech AI

Answer from AI

In the provided main function code, the calls to check_response are executed sequentially because await is used for each call individually. This means that the next request will only start after the previous one has finished, which increases the total execution time.

To run all requests in parallel and reduce the time, you can use asyncio.gather, which runs multiple coroutines simultaneously and waits for their completion:

async def main() -> None:
    await asyncio.gather(
        check_response(delay=2, message="from first line"),
        check_response(delay=2, message="from second line"),
        check_response(delay=2, message="from third line"),
    )

This approach allows all three requests to be executed at the same time, and the total time will be approximately equal to the longest request (about 2 seconds), rather than the sum of all.

Also, note that in the original code, there are commas after the await calls, which are unnecessary and can lead to errors.