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 的串行和并行的主要内容,如果未能解决你的问题,请参考以下文章

并行代码比串行代码慢(值函数迭代示例)

为啥并行和串行版本的执行时间几乎一样

OpenMP 并行代码与串行代码的输出不同

LCD怎么判断串行还是并行

串行输入输出和并行输入输出的区别解析

串行接口和并行接口有啥区别??