0

In the following example, I expect that f1() and f2() can stop after 2s. However, I can run f1() in 3s.

asyncio.wait_for

import asyncio
import time


async def f1():
    print("start sleep")
    time.sleep(3) # simulate CPU intensive part
    print("end sleep")

    print("start asyncio.sleep")
    await asyncio.sleep(3) # simulate IO intensive part
    print("end asyncio.sleep")


async def f2():
    print("start asyncio.sleep")
    await asyncio.sleep(3) # simulate IO intensive part
    print("end asyncio.sleep")

    print("start sleep")
    time.sleep(3) # simulate CPU intensive part
    print("end sleep")


async def main():
    print("-----f1-----")
    t1 = time.time()
    try:
        await asyncio.wait_for(f1(), timeout=2)
    except:
        pass
    t2 = time.time()
    print(f"f1 cost {(t2 - t1)} s")

    print("-----f2-----")
    t1 = time.time()
    try:
        await asyncio.wait_for(f2(), timeout=2)
    except:
        pass
    t2 = time.time()
    print(f"f2 cost {(t2 - t1)} s")


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

the result:

-----f1-----
start sleep
end sleep
start asyncio.sleep
f1 cost 3.0005991458892822 s
-----f2-----
start asyncio.sleep
f2 cost 2.0014591217041016 s

In my practical usecase, f1() has two parts, the first part is CPU intensive and the second part is I/O intensive(only for the 2nd part, I use async syntax). I hope the whole f1() can stop after fixed time. How to implement this usecase?

maplemaple
  • 1,297
  • 6
  • 24
  • 1
    The cause is the order of calls you have defined in `f1` and `f2`. Let us look at the `f2` function, which works as expected. It calls `asyncio.sleep` which has a special implementation to be awaited and does not block I/O while the `time.sleep` does. See the [differences](https://stackoverflow.com/questions/56729764/asyncio-sleep-vs-time-sleep) between `time.sleep` and `asyncio.sleep`. So the `asyncio.wait_for` works only with I/O bound tasks. Note that calling the `time.sleep` inside of an `async` function does not make it I/O bound. – Artyom Vancyan Dec 02 '22 at 08:15
  • @ArtyomVancyan I repost my detailed question here https://stackoverflow.com/questions/74652884/how-to-run-the-whole-async-function-in-given-timeout – maplemaple Dec 02 '22 at 08:39

0 Answers0