码迷,mamicode.com
首页 > 编程语言 > 详细

python 的串行和并行

时间:2020-01-07 20:11:01      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:world   none   run   pytho   control   play   nis   sleep   style   

 

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 的串行和并行

标签:world   none   run   pytho   control   play   nis   sleep   style   

原文地址:https://www.cnblogs.com/sea-stream/p/12163304.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!