Skip to content

Optimize _build_paths_from_predecessors stack logic for 30-40% speedup - #8460

Merged
amcandio merged 7 commits into
networkx:mainfrom
DeepBuha06:optimize-generic-path-construction
Apr 15, 2026
Merged

amcandio merged 7 commits into
networkx:mainfrom
DeepBuha06:optimize-generic-path-construction

Conversation

@DeepBuha06

Copy link
Copy Markdown
Contributor

Description

This PR optimizes the _build_paths_from_predecessors function in networkx/algorithms/shortest_paths/generic.py.

The current implementation manages the stack manually using list indices (stack[top][1] = i + 1) and an explicit top pointer, which is verbose and adds overhead. I have refactored this to use a standard iterator-based stack approach (stack = [[node, iter(children)]]).

This change improves performance significantly for large graphs with many paths while maintaining identical behavior.

Fixes #8459

Improvements

  1. Performance: Consistently 30-40% faster on large graphs (see benchmarks below).
  2. Readability: Reduces code complexity by removing manual index tracking and explicit top pointer manipulation.
  3. Memory: Uses Python iterators, which are generally more memory-efficient than maintaining explicit index integers for every stack level, though the difference is likely negligible compared to the graph size.

Benchmark Results

I benchmarked both implementations using nx.grid_2d_graph(N, N) from $N=2$ to $N=16$. The new implementation shows significant time savings as the number of paths grows.

Test Environment: Grid Graph ($N \times N$), finding all shortest paths from (0,0) to (N-1, N-1).

Grid Size Paths Found Old Time (s) New Time (s) Speedup
10x10 48,620 0.190s 0.105s 1.80x
12x12 705,432 2.55s 1.52s 1.68x
14x14 10,400,600 38.93s 22.21s 1.75x
15x15 40,116,600 153.65s 85.30s 1.80x
16x16 155,117,520 795.19s 494.92s 1.61x

Total Time Saved (16x16): ~300 seconds (5 minutes).

Performance Graph

Benchmark Graph

Implementation Details

Old Approach:

seen = {target}
stack = [[target, 0]]
top = 0
while top >= 0:
    node, i = stack[top]
    if node in sources:
        yield [p for p, n in reversed(stack[: top + 1])]
    if len(pred[node]) > i:
        stack[top][1] = i + 1
        next = pred[node][i]
        if next in seen:
            continue
        else:
            seen.add(next)
        top += 1
        if top == len(stack):
            stack.append([next, 0])
        else:
            stack[top][:] = [next, 0]
    else:
        seen.discard(node)
        top -= 1

New Approach:

stack = [[target, iter(pred[target])]]
path = [target]
seen = {target}

while stack:
    parent, children = stack[-1]
    if parent in sources:
        yield path[::-1]

    for child in children:
        if child not in seen:
            seen.add(child)
            path.append(child)
            stack.append([child, iter(pred[child])])
            break
    else:
        stack.pop()
        path.pop()
        seen.remove(parent)

Verification

  • Ran pytest networkx/algorithms/shortest_paths/tests/test_generic.py - PASSED

@DeepBuha06

Copy link
Copy Markdown
Contributor Author

@dschult @amcandio Thanks for the guidance!

I have pushed the final version which incorporates all the feedback:

  1. Variable Names: Renamed parent/children to node/preds (and predecessor) for better clarity.
  2. Implementation: Retained the list-based stack approach. This avoids the ~8% regression found in the dictionary-based alternative, preserving the full 30-40% speedup over the current codebase.

I think this covers everything we discussed. Let me know if there's anything else, otherwise I'd love to see this merged!

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

I agree with @amcandio that the for/else construction with an if containing the entire body of the loop makes it confusing whether the else with for the for or the if. I see two possible approaches.

  • change the if and add a comment
  • rewrite the loop as a while to check for no more preds left.

First approach:

        for predecessor in preds:
            if predecessor in seen:
                continue
            seen.add(predecessor)
            path.append(predecessor)
            stack.append([predecessor, iter(pred[predecessor])])
            break
        else:  # no preds left!
            stack.pop()
            path.pop()
            seen.remove(node)

Second approach:

        predecessor = next(preds, None)
        while predecessor in seen:
            predecessor = next(preds, None)

        if predecessor is None:  # no preds left!
            stack.pop()
            path.pop()
            seen.remove(node)
        else:
            seen.add(predecessor)
            path.append(predecessor)
            stack.append([predecessor, iter(pred[predecessor])])

Thoughts? Is either better than what's there? Readability is hard to measure. Pick what you think works best. (including leaving it as is)

@DeepBuha06

DeepBuha06 commented Jan 10, 2026 •

Copy link
Copy Markdown
Contributor Author

I think Approach 1 is better.

It definitely clears up the readability confusion, so it's obvious where that else belongs.

I also prefer it because it keeps the standard for loop. since we already saw the dictionary implementation(which relied on manual iteration) was slower, i would rather stick to the native for loop to ensure we keep the C-level optimization and don't risk any overhead from manual next() calls.

I will push the update with the changes you suggested after confirmation!

Final code for confirmation:

 while stack:
        node, preds = stack[-1]
        if node in sources:
            yield path[::-1]

        for predecessor in preds:
            if predecessor in seen:
                continue
            seen.add(predecessor)
            path.append(predecessor)
            stack.append([predecessor, iter(pred[predecessor])])
            break
        else: # no preds left!
            stack.pop()
            path.pop()
            seen.remove(node)

@DeepBuha06

Copy link
Copy Markdown
Contributor Author

@dschult @amcandio
I went ahead and pushed the update (Approach 1) so you can check it out directly. Let me know if it looks good.

@rossbar

rossbar commented Jan 16, 2026

Copy link
Copy Markdown
Contributor

I'm inclined to close this per the agentic PR policy but I don't want the review to go to waste - @amcandio is this worth benchmarking to push forward IYO?

@DeepBuha06

Copy link
Copy Markdown
Contributor Author

Hi @rossbar! Just to clarify, this wasn't an automated submission.

still i am curious to know what made you to think that it was, cause i found this problem and fixing it gave a good amount of speed up, and i showed the data also(using the table and graph). during which amcandio and dschult also helped me to refine it.

@amcandio

Copy link
Copy Markdown
Contributor

I'm inclined to close this per the agentic PR policy but I don't want the review to go to waste - @amcandio is this worth benchmarking to push forward IYO?

Yeah, I think we should be able to merge this one. @DeepBuha06 can you add benchmarks? See other benchmarks examples using asv.

@DeepBuha06

Copy link
Copy Markdown
Contributor Author

okay, I will add that.

@DeepBuha06

Copy link
Copy Markdown
Contributor Author

@amcandio I've added the benchmark class AllShortestPathsGrid to benchmarks/benchmarks/benchmark_shortest_path.py.

i had used List in place of collections.deque before also, but due to which it started to use memory a lot and made time worse. so i changed it to collections.deque with maxlen = 0 to calculate every path but throw it away immediately to save RAM and to find the accurate time.

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

Can you include the output of running asv?

@DeepBuha06

Copy link
Copy Markdown
Contributor Author

@amcandio I've updated the benchmark code to use the clearer for loop structure as requested.

Here is the output from running asv locally:

· Discovering benchmarks
· Running 1 total benchmarks (1 commits * 1 environments * 1 benchmarks)
[ 0.00%] ·· Benchmarking existing-pyC__gsoc networkx_networkx_networkx-dev_Scripts_python.exe
[50.00%] ··· Running (benchmark_shortest_path.AllShortestPathsGrid.time_all_shortest_paths--).
[100.00%] ··· benchmark_shortest_path.AllShortestPathsGrid.time_all_shortest_paths                                  ok
[100.00%] ··· ==== ============
               N
              ---- ------------
               8    5.22±0.4ms
               10    76.6±4ms
               12   1.13±0.03s
              ==== ============

@amcandio

Copy link
Copy Markdown
Contributor

You have to compare it against a commit before the change! See asv docs

@DeepBuha06

Copy link
Copy Markdown
Contributor Author

@amcandio
Since this benchmark class is new and doesn't exist on main, asv compare cannot run directly. Instead, I ran asv run manually on both branches to establish the baseline.

1.) for main branch(old code)

· Discovering benchmarks
· Running 1 total benchmarks (1 commits * 1 environments * 1 benchmarks)
[ 0.00%] ·· Benchmarking existing-pyC__gsoc networkx_networkx_networkx-dev_Scripts_python.exe
[50.00%] ··· Running (benchmark_shortest_path.AllShortestPathsGrid.time_all_shortest_paths--).
[100.00%] ··· benchmark_shortest_path.AllShortestPathsGrid.time_all_shortest_paths                                                                           ok
[100.00%] ··· ==== ===========
               N
              ---- -----------
               8     12.2±1ms
               10    172±4ms
               12   2.59±0.7s
              ==== ===========

2.) for this branch(new/optimized code)

· Discovering benchmarks
· Running 1 total benchmarks (1 commits * 1 environments * 1 benchmarks)
[ 0.00%] ·· Benchmarking existing-pyC__gsoc networkx_networkx_networkx-dev_Scripts_python.exe
[50.00%] ··· Running (benchmark_shortest_path.AllShortestPathsGrid.time_all_shortest_paths--).
[100.00%] ··· benchmark_shortest_path.AllShortestPathsGrid.time_all_shortest_paths                                                                           ok
[100.00%] ··· ==== ============
               N
              ---- ------------
               8    7.20±0.4ms
               10    98.5±2ms
               12   1.47±0.02s
              ==== ============

@amcandio

Copy link
Copy Markdown
Contributor

It is possible to compare two commits using asv. Please check the docs.

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

I'd still be curious to see if this can be refactored to use the dict as a queue instead, but let's not let perfect be the enemy of good!

I'm +1 for the proposed changes on the basis that I find it easier to reason about the proposed queue construction than the previous one (subjective, I know!)

@rossbar

rossbar commented Apr 14, 2026

Copy link
Copy Markdown
Contributor

FWIW you can run the added benchmarks by checking out this branch locally, then:

  1. Modifying asv.conf per your desired environment management approach
  2. Running: asv continuous --bench AllShortestPathsGrid main optimize-generic-path-construction

Once the benchmark is done, a more direct comparison of results can be generated: asv compare main optimize-generic-path-construction

@amcandio
amcandio merged commit c1c468d into networkx:main Apr 15, 2026
46 checks passed
@dschult dschult added this to the 3.7 milestone Apr 15, 2026
@dschult dschult changed the title Optimize _build_paths_from_predecessors stack logic for 30-40% speedup Optimize _build_paths_from_predecessors stack logic for 30-40% speedup Sep 3, 2026
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.

Optimize _build_paths_from_predecessors stack logic for 30-40% speedup

4 participants