异步IO Python语法-多进程、多线程、协程( 四 )

 
asyncio 1234567891011121314151617181920import asyncioimport timeasync def query(num):print(num)await asyncio.sleep(1)async def main():tasks = [asyncio.create_task(query(num)) for num in range(10)]await asyncio.gather(*tasks)# main entranceif __name__ == '__main__':start_time = time.perf_counter()asyncio.run(main())end_time = time.perf_counter()print(f"时间差:{end_time-start_time}")  
asyncio+uvloop注意

windows上不支持uvloop 。
示例
12345678910111213141516171819202122import asyncioimport uvloopimport timeasync def query(num):print(num)await asyncio.sleep(1)async def main():tasks = [asyncio.create_task(query(host)) for host in range(10)]await asyncio.gather(*tasks)# main entranceif __name__ == '__main__':uvloop.install()start_time = time.perf_counter()asyncio.run(main())end_time = time.perf_counter()print(f"时间差:{end_time-start_time}")  
运行时间对比 方式
运行时间
串行
10.0750972s
多进程
1.1638731999999998s
多线程
1.0146456s
asyncio
1.0110082s
asyncio+uvloop
1.01s
 


推荐阅读