# Python應用Asynchronous *初探異步/同步* ###### tags: `python` Copyright 2021, [月下麒麟](https://hackmd.io/@YMont/note-catalog) --- ## Objectives 了解Python應用異步/同步的用法與行為 並做個簡單的紀錄 ## Source Code ```python= import asyncio import time now = lambda: time.time() def dosomething(num): print('第 {} 任務,第一步'.format(num)) time.sleep(2) print('第 {} 任務,第二步'.format(num)) async def dosomething2(num): print('第 {} 任務,第一步'.format(num)) await asyncio.sleep(2) print('第 {} 任務,第二步'.format(num)) if __name__ == "__main__": start = now() tasks = [dosomething(i) for i in range(5)] print('TIME: ', now() - start) # ------------ start = now() tasks = [dosomething2(i) for i in range(5)] asyncio.run(asyncio.wait(tasks)) print('TIME: ', now() - start) ``` ![](https://i.imgur.com/wGltsKJ.png) 函式1使用一般同步的回應方式,執行需要花費10秒左右 函式2使用一般異步的回應方式,執行僅需花費2秒左右 Reference:[【Python教學】淺談 Coroutine 協程使用方法](https://www.maxlist.xyz/2020/03/29/python-coroutine/)