- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我必须发送很多 HTTP 请求,一旦所有请求都返回,程序才能继续。听起来非常适合 asyncio
。有点天真,我将对 requests
的调用包装在 async
函数中,并将它们交给 asyncio
。这是行不通的。
在网上搜索后,找到了两种解决方案:
asyncio
run_in_executor
的调用中为了更好地理解这一点,我编写了一个小型基准测试。服务器端是一个 flask 程序,在响应请求之前等待 0.1 秒。
from flask import Flask
import time
app = Flask(__name__)
@app.route('/')
def hello_world():
time.sleep(0.1) // heavy calculations here :)
return 'Hello World!'
if __name__ == '__main__':
app.run()
客户是我的标杆
import requests
from time import perf_counter, sleep
# this is the baseline, sequential calls to requests.get
start = perf_counter()
for i in range(10):
r = requests.get("http://127.0.0.1:5000/")
stop = perf_counter()
print(f"synchronous took {stop-start} seconds") # 1.062 secs
# now the naive asyncio version
import asyncio
loop = asyncio.get_event_loop()
async def get_response():
r = requests.get("http://127.0.0.1:5000/")
start = perf_counter()
loop.run_until_complete(asyncio.gather(*[get_response() for i in range(10)]))
stop = perf_counter()
print(f"asynchronous took {stop-start} seconds") # 1.049 secs
# the fast asyncio version
start = perf_counter()
loop.run_until_complete(asyncio.gather(
*[loop.run_in_executor(None, requests.get, 'http://127.0.0.1:5000/') for i in range(10)]))
stop = perf_counter()
print(f"asynchronous (executor) took {stop-start} seconds") # 0.122 secs
#finally, aiohttp
import aiohttp
async def get_response(session):
async with session.get("http://127.0.0.1:5000/") as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
await get_response(session)
start = perf_counter()
loop.run_until_complete(asyncio.gather(*[main() for i in range(10)]))
stop = perf_counter()
print(f"aiohttp took {stop-start} seconds") # 0.121 secs
因此,使用 asyncio
的直观实现不会处理阻塞 io 代码。但是如果你正确使用asyncio
,它和特殊的aiohttp
框架一样快。 coroutines and tasks 的文档真的不要提这个。只有当你阅读了loop.run_in_executor() ,它说:
# File operations (such as logging) can block the
# event loop: run them in a thread pool.
我对这种行为感到惊讶。 asyncio 的目的是加速阻塞 io 调用。为什么需要额外的包装器 run_in_executor
来执行此操作?
aiohttp
的全部卖点似乎是对asyncio
的支持。但据我所知,requests
模块工作得很好——只要你把它包装在一个执行器中。是否有理由避免在执行程序中包装某些东西?
最佳答案
But as far as I can see, the requests module works perfectly - as long as you wrap it in an executor. Is there a reason to avoid wrapping something in an executor ?
Running code in executor 表示在OS threads中运行.
aiohttp
和类似的库允许在没有操作系统线程的情况下运行非阻塞代码,仅使用协程。
如果您没有太多工作,操作系统线程和协程之间的差异并不显着,尤其是与瓶颈 - I/O 操作相比。但是一旦你有很多工作,你会注意到由于昂贵的 context switching,操作系统线程的性能相对较差。 .
例如,当我将您的代码更改为time.sleep(0.001)
和range(100)
时,我的机器显示:
asynchronous (executor) took 0.21461606299999997 seconds
aiohttp took 0.12484742700000007 seconds
并且这种差异只会根据请求的数量而增加。
The purpose of asyncio is to speed up blocking io calls.
不,asyncio
的目的是提供方便的方式来控制执行流程。 asyncio
允许您选择流程的工作方式 - 基于协程和操作系统线程(当您使用执行器时)或纯协程(如 aiohttp
所做的)。
aiohttp
的目的是加快速度,它处理如上所示的任务:)
关于python - 为什么 asyncio 不总是使用执行器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53260688/
我正在我的一个项目中使用 aiohttp 并想限制每秒发出的请求数。我正在使用 asyncio.Semaphore 来做到这一点。我的挑战是我可能想要增加/减少每秒允许的请求数。 例如: limit
如何混合 async with api.open() as o: ... 和 o = await api.open() 在一个功能中? 自从第一次需要带有 __aenter__ 的对象以来和
有 2 个工作:“wash_clothes”(job1) 和“setup_cleaning_robot”(job2),每个工作需要你 7 和 3 秒,你必须做到世界末日。 这是我的代码: import
我们有一种设置线程名称的方法:thread = threading.Thread(name='Very important thread', target=foo),然后在格式化程序中使用 %(thr
我有一些代码,用于抓取 URL、解析信息,然后使用 SQLAlchemy 将其放入数据库中。我尝试异步执行此操作,同时限制同时请求的最大数量。 这是我的代码: async def get_url(ai
1>Python Asyncio 未使用 asyncio.run_coroutine_threadsafe 运行新的协程。下面是在Mac上进行的代码测试。 ——————————————————————
asyncio.gather和 asyncio.wait似乎有类似的用途:我有一堆我想要执行/等待的异步事情(不一定要在下一个开始之前等待一个完成)。它们使用不同的语法,并且在某些细节上有所不同,但对
我正在尝试使用 asyncio 运行以下程序: import asyncio async def main(): print('Hello') await asyncio.sleep(
我正在尝试在事件循环之外使用协程函数。 (在这种情况下,我想在 Django 中调用一个也可以在事件循环中使用的函数) 如果不使调用函数成为协程,似乎没有办法做到这一点。 我意识到 Django 是为
我有一个假设 asyncio.gather设想: await asyncio.gather( cor1, [cor2, cor3], cor4, ) 我要 cor2和 cor3
我有多个服务器,每个服务器都是 asyncio.start_server 返回的实例。我需要我的 web_server 与 websockets 一起使用,以便能够使用我的 javascript 客户
我正在使用 Python 3 asyncio 框架评估定期执行的不同模式(为简洁起见省略了实际 sleep /延迟),我有两段代码表现不同,我无法解释原因。第一个版本使用 yield from 递归调
从事件线程外部将协程推送到事件线程的 pythonic 方法是什么? 最佳答案 更新信息: 从Python 3.7 高级函数asyncio.create_task(coro)开始was added并且
我有一个大型 (1M) 数据库结果集,我想为其每一行调用一个 REST API。 API 可以接受批处理请求,但我不确定如何分割 rows 生成器,以便每个任务处理一个行列表,比如 10。我宁愿不预先
迷失在异步中。 我同时在学习Kivy和asyncio,卡在了解决运行Kivy和运行asyncio循环的问题上,无论怎么转,都是阻塞调用,需要顺序执行(好吧,我希望我是错的),例如 loop = asy
我有这个 3.6 异步代码: async def send(command,userPath,token): async with websockets.connect('wss://127.
首先,我需要警告你:我是 asyncio 的新手,而且我是 我马上警告你,我是 asyncio 的新手,我很难想象引擎盖下的库里有什么。 这是我的代码: import asyncio semaphor
我有一个asyncio.PriorityQueue,用作网络爬虫的URL队列,当我调用url_queue.get时,得分最低的URL首先从队列中删除()。当队列达到 maxsize 项时,默认行为是阻
探索 Python 3.4.0 的 asyncio 模块,我试图创建一个类,其中包含从类外部的 event_loop 调用的 asyncio.coroutine 方法。 我的工作代码如下。 impor
我有一个可能是无用的问题,但尽管如此,我还是觉得我错过了一些对于理解 asyncio 的工作方式可能很重要的东西。 我刚刚开始熟悉 asyncio 并编写了这段非常基本的代码: import asyn
我是一名优秀的程序员,十分优秀!