Skip to content

Fix weakly_connected_components() performance on graph view - #7586

Merged
rossbar merged 4 commits into
networkx:mainfrom
gregory-shklover:main
Aug 6, 2024
Merged

rossbar merged 4 commits into
networkx:mainfrom
gregory-shklover:main

Conversation

@gregory-shklover

@gregory-shklover gregory-shklover commented Aug 1, 2024 •

Copy link
Copy Markdown
Contributor

Description

weakly_connected_components() calls len(G) inside a loop, resulting in poor performance on graph views.
suggested pull request moves len(G) to outside the loop.

Reproduction:

import datetime
import os.path
import sys

sys.path.insert(0, os.path.dirname(__file__))
from networkx import DiGraph, weakly_connected_components, subgraph_view

g = DiGraph()
for i in range(10_000):
    g.add_node(i)

view = subgraph_view(g, filter_node=lambda n: True, filter_edge=lambda u, v: True)

for i in range(10):
    start = datetime.datetime.now()
    for c in weakly_connected_components(view):
        pass
    end = datetime.datetime.now()
    tmp = None
    print(f'{(end - start).total_seconds():.9f}')

Evaluation results:

  • before fix: ~15.4sec per iteration
  • after fix: 0.064sec per iteration

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks a lot for this subtle and impactful change!

@Peiffap Peiffap left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Good catch! We could perhaps make the same change in networkx/algorithms/components/connected.py, while we're at it.

@gregory-shklover

Copy link
Copy Markdown
Contributor Author

Updated connected.py as well

@Peiffap Peiffap left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks!

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@rossbar
rossbar merged commit 2516c15 into networkx:main Aug 6, 2024
@dschult dschult added this to the 3.4 milestone Aug 28, 2024
rossbar pushed a commit to Peiffap/networkx that referenced this pull request Sep 6, 2024
…#7586)

* Fix weakly_connected_components() performance

* Applied the same fix for connected.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

5 participants