python 异步调用
生活随笔
收集整理的這篇文章主要介紹了
python 异步调用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
最近遇到個問題,?NLP相關的代碼,尤其是DL相關的代碼,處理千萬級數據顯得會慢一些,有可能要好幾個小時,那前端的等待是不可行的,這個時候就需要采用python的異步函數了。
同步代碼
import timedef hello():time.sleep(1)def run():for i in range(5):hello()print('Hello World:%s' % time.time()) if __name__ == '__main__':run()Hello World:1536842494.2786784 Hello World:1536842495.2796268 Hello World:1536842496.2802596 Hello World:1536842497.2804587 Hello World:1536842498.2812462異步代碼
import time import asyncio# 定義異步函數 async def hello():print('Hello World:%s' % time.time())#必須使用await,不能使用yield from;如果是使用yield from ,需要采用@asyncio.coroutine相對應await asyncio.sleep(1) print('Hello wow World:%s' % time.time())def run():tasks = []for i in range(5):tasks.append(hello())loop.run_until_complete(asyncio.wait(tasks))loop = asyncio.get_event_loop() if __name__ =='__main__':run()Hello World:1536855050.1950748 Hello World:1536855050.1950748 Hello World:1536855050.1950748 Hello World:1536855050.1960726 Hello World:1536855050.1960726 (暫停約1秒) Hello wow World:1536855051.1993241 Hello wow World:1536855051.1993241 Hello wow World:1536855051.1993241 Hello wow World:1536855051.1993241 Hello wow World:1536855051.1993241?
具體可以參加以下鏈接:
https://blog.csdn.net/brucewong0516/article/details/82697935
https://www.ruanyifeng.com/blog/2019/11/python-asyncio.html
https://www.cnblogs.com/sui776265233/p/10950001.html
?
總結
以上是生活随笔為你收集整理的python 异步调用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 九阳真经之vi大法
- 下一篇: Spring 接口方法异步调用