Skip to content

Commit

Permalink
[PR #8660/14d5295 backport][3.10] Improve performance of WebSockets w…
Browse files Browse the repository at this point in the history
…hen there is no timeout (#8663)
  • Loading branch information
bdraco committed Aug 9, 2024
1 parent 1bc8d53 commit 3a9de0c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
3 changes: 3 additions & 0 deletions CHANGES/8660.misc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Improved performance of :py:meth:`~aiohttp.ClientWebSocketResponse.receive` and :py:meth:`~aiohttp.web.WebSocketResponse.receive` when there is no timeout. -- by :user:`bdraco`.

The timeout context manager is now avoided when there is no timeout as it accounted for up to 50% of the time spent in the :py:meth:`~aiohttp.ClientWebSocketResponse.receive` and :py:meth:`~aiohttp.web.WebSocketResponse.receive` methods.
11 changes: 10 additions & 1 deletion aiohttp/client_ws.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,8 @@ async def close(self, *, code: int = WSCloseCode.OK, message: bytes = b"") -> bo
return False

async def receive(self, timeout: Optional[float] = None) -> WSMessage:
receive_timeout = timeout or self._receive_timeout

while True:
if self._waiting:
raise RuntimeError("Concurrent call to receive() is not allowed")
Expand All @@ -294,7 +296,14 @@ async def receive(self, timeout: Optional[float] = None) -> WSMessage:
try:
self._waiting = True
try:
async with async_timeout.timeout(timeout or self._receive_timeout):
if receive_timeout:
# Entering the context manager and creating
# Timeout() object can take almost 50% of the
# run time in this loop so we avoid it if
# there is no read timeout.
async with async_timeout.timeout(receive_timeout):
msg = await self._reader.read()
else:
msg = await self._reader.read()
self._reset_heartbeat()
finally:
Expand Down
10 changes: 9 additions & 1 deletion aiohttp/web_ws.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,7 @@ async def receive(self, timeout: Optional[float] = None) -> WSMessage:

loop = self._loop
assert loop is not None
receive_timeout = timeout or self._receive_timeout
while True:
if self._waiting:
raise RuntimeError("Concurrent call to receive() is not allowed")
Expand All @@ -499,7 +500,14 @@ async def receive(self, timeout: Optional[float] = None) -> WSMessage:
try:
self._waiting = True
try:
async with async_timeout.timeout(timeout or self._receive_timeout):
if receive_timeout:
# Entering the context manager and creating
# Timeout() object can take almost 50% of the
# run time in this loop so we avoid it if
# there is no read timeout.
async with async_timeout.timeout(receive_timeout):
msg = await self._reader.read()
else:
msg = await self._reader.read()
self._reset_heartbeat()
finally:
Expand Down

0 comments on commit 3a9de0c

Please sign in to comment.