【问题标题】:Python async/await difference in execution timePython async/await 执行时间的差异
【发布时间】:2019-03-21 21:12:49
【问题描述】:

我正在使用异步 io 计时两种执行方法

案例 1:

async def test():    
    print(f"started at {time.strftime('%X')}")
    await asyncio.create_task(say_after(2, 'hello'))
    await asyncio.create_task(say_after(4, 'world'))    
    print(f"finished at {time.strftime('%X')}")

它的响应是:

started at 12:31:05
hello
world
finished at 12:31:11

总共 6 秒

案例 2:

async def test():    
    print(f"started at {time.strftime('%X')}")
    t1=asyncio.create_task(say_after(2, 'hello'))
    t2= asyncio.create_task(say_after(4, 'world'))    
    await t1
    await t2
    print(f"finished at {time.strftime('%X')}")

它的响应是:

started at 12:31:05
hello
world
finished at 12:31:09

总共 4 秒

为什么会这样?

【问题讨论】:

  • 因为任务在创建时开始执行,这意味着如果您首先创建两个任务,您将让您的任务“并行”运行,然后等待它们(因为第一个任务将达到暂停状态(say_after),然后允许下一个任务开始。

标签: python python-3.x async-await python-asyncio


【解决方案1】:

在第一个示例中,您在询问时创建,等待它完成,然后创建另一个任务,并等待另一个任务完成。您正在按顺序执行任务。

在第二个示例中,您正在创建两个任务,然后在它们都创建后,等待两个任务完成。您正在同时执行任务。

任务一个接一个地执行需要 2 + 4 = 6 秒,但是当连续执行时,您只需要等待 4 秒即可等待第二个较长的任务完成,而较短的 2 秒任务在一段时间之前完成那么:

# sequentially

| start task 1
V
+-------------+
| 2 seconds   |
+-------------+
              ^
await returns |

                | start task 2
                V
                +--------------------------+
                | 4 seconds                |
                +--------------------------+
                                           ^
                             await returns |

# consecutively

| start task 1
V
+-------------+
| 2 seconds   |
+-------------+
              ^
await returns |

| start task 2
V
+--------------------------+
| 4 seconds                |
+--------------------------+
                           ^
             await returns |

区别在于调用asyncio.create_task() 而不 立即等待任务,因为await task 在任务完成之前不会完成。

Tasks section of the Awaitables documentation中有一个例子:

async def main():
    # Schedule nested() to run soon concurrently
    # with "main()".
    task = asyncio.create_task(nested())

    # "task" can now be used to cancel "nested()", or
    # can simply be awaited to wait until it is complete:
    await task

注意调度nested() 很快就会与“main()” 和同时运行,或者可以简单地等待直到它完成 cmets。 p>

任务是专门的 Future 子类,因此 documentation for asyncio.Future 在这里也很重要:

Future 是一个可等待的对象。协程可以等待 Future 对象,直到它们有结果或异常集,或者直到它们被取消。

【讨论】:

  • 文档应该添加这个,基本上 await t1 以防万一不需要 2,因为 await t2 将等待 4 秒。谢谢
  • @JibinMathews:这取决于应用程序,文档无法告诉您何时等待何时不等待。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-14
  • 2019-05-24
  • 1970-01-01
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
  • 2018-12-15
相关资源
最近更新 更多