Skip to content

gh-104144: Optimize gather to finish eagerly when all futures complete eagerly #104138

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 6, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions Lib/asyncio/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -815,6 +815,7 @@ def _done_callback(fut):
nfinished = 0
loop = None
outer = None # bpo-46672
all_finished = True
for arg in coros_or_futures:
if arg not in arg_to_fut:
fut = ensure_future(arg, loop=loop)
Expand All @@ -829,15 +830,26 @@ def _done_callback(fut):

nfuts += 1
arg_to_fut[arg] = fut
fut.add_done_callback(_done_callback)
if fut.done():
# call the callback immediately instead of scheduling it
_done_callback(fut)
else:
all_finished = False
fut.add_done_callback(_done_callback)

else:
# There's a duplicate Future object in coros_or_futures.
fut = arg_to_fut[arg]

children.append(fut)

outer = _GatheringFuture(children, loop=loop)
if all_finished:
# optimization: skip creating GatheringFuture if all children completed
# (e.g. when all coros are able to complete eagerly)
outer = futures.Future(loop=loop)
outer.set_result([c.result for c in children])
else:
outer = _GatheringFuture(children, loop=loop)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
outer = _GatheringFuture(children, loop=loop)
outer.__self_log_traceback = False
outer = _GatheringFuture(children, loop=loop)

return outer


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Optimize asyncio.gather when using eager tasks factory Skip creating
gathering future and scheduling done callbacks when all futures finish
without blocking - for up to 3x speedup