⚡️ Speed up function find_cycle_vertices
by 214%
#83
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 214% (2.14x) speedup for
find_cycle_vertices
insrc/dsa/nodes.py
⏱️ Runtime :
48.9 milliseconds
→15.6 milliseconds
(best of170
runs)📝 Explanation and details
The optimized code replaces the expensive
nx.simple_cycles()
call withnx.strongly_connected_components()
, delivering a 214% speedup by fundamentally changing the algorithm approach.Key Optimization:
nx.simple_cycles()
- computationally expensive as it must find and traverse every possible cycle pathWhy This Works:
A vertex participates in a cycle if and only if:
Performance Analysis:
From the line profiler, the original spends 89.4% of time in
nx.simple_cycles()
, while the optimized version distributes work across SCC analysis (65.5%) and component processing. The SCC approach scales much better - it processes components once rather than enumerating all possible cycle paths.Test Case Performance:
graph.has_edge(vertex, vertex)
for each single-vertex SCCThe optimization is particularly effective for real-world graphs with complex cycle structures where the original algorithm's cycle enumeration becomes prohibitively expensive.
✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
test_dsa_nodes.py::test_complex_graph
test_dsa_nodes.py::test_cycle_with_extra_nodes_edges
test_dsa_nodes.py::test_figure_eight
test_dsa_nodes.py::test_multiple_disjoint_cycles
test_dsa_nodes.py::test_multiple_overlapping_cycles
test_dsa_nodes.py::test_no_cycles_dag
test_dsa_nodes.py::test_self_loop
test_dsa_nodes.py::test_simple_triangle_cycle
test_dsa_nodes.py::test_simple_two_node_cycle
test_dsa_nodes.py::test_string_vertices
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-find_cycle_vertices-mejgju1v
and push.