• 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

  • 相关阅读:
    本周学习进度
    梦断代码阅读笔记01
    站立会议06(第二期)
    计算机软件方面的面试题?
    算法Bai-Piao
    哈希表
    关于编写代码的一些建议
    使用Promise
    Lintcode
    搭建Android浏览器壳子
  • 原文地址:https://www.cnblogs.com/sea-stream/p/12163304.html
Copyright © 2020-2023  润新知