Skip to content

Speed up connected_components and weakly_connected_components - #7971

Merged
Schefflera-Arboricola merged 1 commit into
networkx:mainfrom
amcandio:is_connected_speedup
Apr 30, 2025
Merged

Schefflera-Arboricola merged 1 commit into
networkx:mainfrom
amcandio:is_connected_speedup

Conversation

@amcandio

@amcandio amcandio commented Apr 14, 2025 •

Copy link
Copy Markdown
Contributor

Speed up connected_components and weakly_connected_components

This PR introduces lightweight optimizations to several connectivity-checking functions by adding early returns based on simple graph invariants. These heuristics help short-circuit computation in cases where connectivity can be ruled out without traversing the graph.

Summary of changes:

  • Adjusted BFS calls in connected_components and weakly_connected_components to reduce traversal overhead when many nodes have already been seen.

These changes preserve correctness while reducing unnecessary work, especially on dense graphs.

Performance improvements results

The optimization shows the most significant gains on disconnected graphs with large components, achieving up to a 367× speed-up for n=1000. This case is artificially generated to make current version need to visit the same nodes in a connected component multiple times. These are the types of cases where optimization works best.

For connected and random graphs, performance changes are generally smaller, often within a ±10% range. In a few low-n random graph cases, the optimized version was marginally slower, likely due to overhead not offset by structural gains.

Overall, the optimization is highly effective in worst-case disconnected scenarios while maintaining neutral or slightly improved performance elsewhere.

Single Node + Complete Component (Disconnected, 100 runs)

n Without Optimization (s) With Optimization (s) Speed-up
10 0.000008 0.000004 2.00× (faster)
100 0.000552 0.000017 32.47× (faster)
1000 0.049941 0.000136 367.21× (faster)

Random Graphs (p=0.01, 10000 runs each)

n Seed Without Optimization (s) With Optimization (s) Speed-up
10 42 0.000008 0.000015 0.53× (slower)
10 99 0.000007 0.000008 0.88× (slower)
10 123 0.000007 0.000009 0.78× (slower)
100 42 0.000048 0.000047 1.02× (faster)
100 99 0.000047 0.000053 0.89× (slower)
100 123 0.000051 0.000049 1.04× (faster)
1000 42 0.000597 0.000577 1.03× (faster)
1000 99 0.000785 0.000733 1.07× (faster)
1000 123 0.000688 0.000614 1.12× (faster)

Connected Graphs (Complete Graphs, 10000 runs)

n Without Optimization (s) With Optimization (s) Speed-up
10 0.000003 0.000003 1.00× (same)
100 0.000018 0.000016 1.13× (faster)
1000 0.000149 0.000142 1.05× (faster)

Benchmark code

import networkx as nx
import timeit

def measure_runtime(func, runs=100):
    """Measure average runtime over multiple runs."""
    timer = timeit.Timer(func)
    times = timer.repeat(repeat=1, number=runs)
    return times[0] / runs

def random_graph_test(ns, p, seeds, runs=100):
    print(f"\n=== Random Graphs (p={p}, {runs} runs each) ===")
    for n in ns:
        for seed in seeds:
            G = nx.erdos_renyi_graph(n, p, seed=seed)
            def run():
                list(nx.connected_components(G))
            t = measure_runtime(run, runs)
            print(f"n={n}, seed={seed}: {t:.6f} seconds")

def connected_graph_test(ns, runs=100):
    print(f"\n=== Connected Graphs (Complete Graphs, {runs} runs) ===")
    for n in ns:
        G = nx.complete_graph(n)
        def run():
            list(nx.connected_components(G))
        t = measure_runtime(run, runs)
        print(f"n={n}: {t:.6f} seconds")

def single_and_complete_component_test(ns, runs=100):
    print(f"\n=== Single Node + Complete Component (Disconnected, {runs} runs) ===")
    for n in ns:
        G = nx.Graph()
        G.add_node(0)
        G.add_edges_from((i, j) for i in range(1, n) for j in range(i + 1, n))
        def run():
            list(nx.connected_components(G))
        t = measure_runtime(run, runs)
        print(f"n={n}: {t:.6f} seconds")

if __name__ == "__main__":
    Ns = [10, 100, 1000]
    P = 0.01
    SEEDS = [42, 99, 123]

    random_graph_test(Ns, P, SEEDS, runs=10_000)
    connected_graph_test(Ns, runs=10_000)
    single_and_complete_component_test(Ns, runs=100)

@dschult

dschult commented Apr 14, 2025

Copy link
Copy Markdown
Member

There is some computational cost to networkx counting the number of edges. It is about a third the time of using bfs_edges for 1000 nodes. And it should scale with number of nodes instead of number of edges.So I think this should be effective as a shortcut approach.

Are there cases when a user would probably not want these shortcuts computed? For the case of 1000 nodes, I estimate it would take 465us instead of 350us (~30% longer) for a non-shortcut result. And 115us for the shortcut case. But those estimates are not using this code.

If that's an issue we could add a kwarg to turn on (or off) the shortcut feature. Thoughts?

@amcandio

Copy link
Copy Markdown
Contributor Author

Ah, I did not know that! I suspected len was expensive after seeing some comments in the code. What is the historical context for those fields to not be cached?

@dschult

dschult commented Apr 14, 2025

Copy link
Copy Markdown
Member

len is typically fast -- so len(G) is too. But we have to compute the len of each nbrdict in the dict-of-dict data structure. I think of it as being quick O(n) -- but then I think of is_connected as being quick too O(n+m) = O(m) :)

In terms of caching, we thought about caching way back in the day -- and some factors led us not to choose it:

  • caching updates do slow down building and changing the graph and many algorithms/codepaths never use it
  • the data structure could be changed directly by users without our knowing about it (not so true anymore -- views kind of discourage that kind of grow-your-own approach).
  • there is a simplicity to the data structure without caching (again views detract from that argument
  • it seemed at the time, that the user could easily cache the result themselves and use it where needed.

Another data structure could have avoided this issue -- if we had the dict-of-dict point to the relevant edge info within a list of edge info dicts. Then the number of (unweighted) edges would be fast: len(edge_info_list).

That's the history of it -- but the history leading to no caching doesn't mean we can't start caching now -- of course, we should take into account these factors in our decision.

I did a little more testing, and it looks like for G=nx.binomial_graph(10_000, 0.0001) that %timeit G.number_of_edges() gives 1.12ms while %timeit nx.is_connected(G) takes 21us. So there must be features of the code that make these large graphs with few edges fast already. Have you done some tests with this PR? Which cases lead to improvements?

@amcandio
amcandio force-pushed the is_connected_speedup branch from 78d122c to 9314c2d Compare April 15, 2025 06:52
@amcandio amcandio changed the title Is connected speedup [Draft] Potential Speed up connected_components and weakly_connected_components Apr 15, 2025
@amcandio

amcandio commented Apr 15, 2025 •

Copy link
Copy Markdown
Contributor Author

Thanks for the context! I believe adding caching would unblock many optimizations like this.

So there must be features of the code that make these large graphs with few edges fast already

Yes, I can see why now. It's because DFS is exiting early while edge counting needs to visit all edges.

Have you done some tests with this PR? Which cases lead to improvements?

Not many besides a quick check with an adverse graph. I was so convinced len(G.edges()) was O(1) that I left that for when finishing up the PR. I removed those optimizations for now (hopefully we can add them in some future).

I updated the PR and left only the optimization for the DFS but need to spend some time to get better measurements.

@amcandio
amcandio marked this pull request as ready for review April 30, 2025 13:46
@amcandio amcandio changed the title [Draft] Potential Speed up connected_components and weakly_connected_components Speed up connected_components and weakly_connected_components Apr 30, 2025
@amcandio

Copy link
Copy Markdown
Contributor Author

Hey @dschult I got time to come back to this. I removed the number of edges optimizations because they were actually slower, leaving the PR with only the BFS stop-early optimization.

I'm seeing very good results on graphs where one big component is explored last. For the rest of tested graphs, I see small mixed results. What do you think?

@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.

This is a good straight-forward speedup of our finding components. I believe it is an oversight of the original code. The _plain_bfs takes the argument n so that it can check if the bfs has found every node. So when we switch to a new component we can update that number to have it hopefully work for us on the last component.

Thanks!

@Schefflera-Arboricola Schefflera-Arboricola 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 @amcandio and @dschult !

@Schefflera-Arboricola
Schefflera-Arboricola merged commit 3d0bb21 into networkx:main Apr 30, 2025
@amcandio
amcandio deleted the is_connected_speedup branch April 30, 2025 18:11
@jarrodmillman jarrodmillman added this to the 3.5 milestone May 29, 2025
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.

4 participants