⚡️ Speed up function lemke_howson
by 14%
#9
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.
📄 14% (0.14x) speedup for
lemke_howson
inquantecon/game_theory/lemke_howson.py
⏱️ Runtime :
499 microseconds
→438 microseconds
(best of695
runs)📝 Explanation and details
The optimized code achieves a 13% speedup through several focused performance improvements:
Key optimizations:
Reduced arithmetic overhead: Replaced
sum(nums_actions)
with direct additionnums_actions[0] + nums_actions[1]
, eliminating function call overhead for this simple 2-element case.Faster type checking: Changed
isinstance(init_pivot, numbers.Integral)
to a hybrid approach usingtype(init_pivot) is not int
first, which is much faster for the common case of actualint
types, falling back toisinstance
only when needed.Pre-computed array sizes: Hoisted
row_sizes = (nums_actions[1], nums_actions[0])
calculation outside the tuple creation, avoiding repeated indexing operations during array allocation.Enhanced JIT compilation: Added
fastmath=True
,nogil=True
, andinline='always'
to_get_mixed_actions
, enabling more aggressive Numba optimizations for the mathematical operations.Streamlined modular arithmetic: In
_lemke_howson_capping
, cachedm_plus_n = m + n
to avoid repeated addition and usedmin()
replacement with conditional for better branch prediction.Loop optimizations: Unrolled the generic loop in
_get_mixed_actions
into explicit cases for the 2-player scenario, allowing Numba to optimize more effectively.The optimizations are particularly effective for small to medium games (like the 2x2, 3x2 test cases showing 22-33% improvements) where setup overhead was a significant portion of runtime. For larger games, the improvements are more modest (4-12%) as the algorithmic complexity dominates, but the optimizations still provide consistent gains across all test cases.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-lemke_howson-mgg0zcbj
and push.