python 的串行和并行
Posted F
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 的串行和并行相关的知识,希望对你有一定的参考价值。
import asyncio import time #串行 #asyncio.run() async def say_after(delay, what): await asyncio.sleep(delay) print(what) async def main(): print(f"started at {time.strftime(‘%X‘)}") await say_after(2, ‘hello‘) await say_after(1, ‘world‘) print(f"finished at {time.strftime(‘%X‘)}") asyncio.run(main()) #并行 #asyncio.create_task() async def say_after(delay, what): await asyncio.sleep(delay) print(what) async def main(): task1 = asyncio.create_task( say_after(2, ‘hello‘)) task2 = asyncio.create_task( say_after(1, ‘world‘)) print(f"started at {time.strftime(‘%X‘)}") # Wait until both tasks are completed (should take # around 2 seconds.) await task1 await task2 print(f"finished at {time.strftime(‘%X‘)}") asyncio.run(main())
输出
started at 19:20:48 hello world finished at 19:20:51 started at 19:20:51 world hello finished at 19:20:53
以上是关于python 的串行和并行的主要内容,如果未能解决你的问题,请参考以下文章