scc: speed up iterative DFS by dropping tuple-based stack simulation - #36
Merged
Conversation
The previous implementation pushed (v, bef, t) tuples onto the stack to simulate recursion, allocating up to two tuples per edge and, in graphs where multiple frontier nodes share an undiscovered neighbor, pushing duplicate entries that had to be detected and discarded later. Replace it with the standard technique of keeping one stack frame per active vertex, paired with a resumable edge-iterator index, so each vertex is pushed at most once and each edge is scanned once. This avoids per-edge tuple allocation/unpacking and closure variable lookups from the nested dfs() function. Verified against the previous implementation with randomized differential testing (thousands of graphs) for identical output, and benchmarked 1.2x-2.3x faster across random, chain, cycle, and fan-in graphs up to 300k vertices.
📊 Performance Benchmark Results⏱️ Execution time (mean, lower is better)
💾 Peak memory (lower is better)
Base = target branch, PR = this branch. Negative delta = improvement. ✅ improvement ≥ 1%, |
Closed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
scc()simulated recursion by pushing(v, bef, t)tuples onto a stack — up to two tuple allocations per edge, plus duplicate pushes when multiple frontier nodes shared an undiscovered neighbor (detected and discarded later at pop time).dfs()closure into the main function body to avoidLOAD_DEREFoverhead onlow/Ord/visited.Why
Reported that stuffing tuples onto the stack looked like the bottleneck in
scc(); profiling/benchmarking confirmed it.Test plan
python3 -m unittest discover -s tests— all 146 existing tests pass (includingtwo_sat.py, which depends onscc)benchmarks/workloads.pyalready includes ansccworkload for the perf-comparison CIGenerated by Claude Code