asyncio
1234567891011121314151617181920
import 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 。示例
12345678910111213141516171819202122
import 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
推荐阅读
- 2022 python图形界面框架推荐
- 初识python正则表达式
- Python垃圾回收机制,人生苦短,只谈风月,谈什么回收?
- Python实现天气查询功能
- 用Python爬取六大平台的弹幕、评论,看这一篇就够了
- Python 中的自然语言处理入门
- 用python帮别人写了个文字识别程序
- 3个提升Python运行速度的方法,很实用
- 手把手教你编写Python抢购脚本
- Python生成遍历暴力破解密码,实战的效果差强人意了