⚡️ Speed up function _temporal_context
by 13%
#3
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.
📄 13% (0.13x) speedup for
_temporal_context
intemporalio/nexus/_operation_context.py
⏱️ Runtime :
27.8 microseconds
→24.5 microseconds
(best of66
runs)📝 Explanation and details
The optimization inlines the context retrieval logic directly into
_temporal_context
, eliminating a function call overhead.Key changes:
start_ctx
andcancel_ctx
retrieval from_try_temporal_context()
directly into_temporal_context()
Why this is faster:
_temporal_context()
calling_try_temporal_context()
, which involved stack frame creation, parameter passing, and return value handlingPerformance characteristics:
The optimization is particularly effective for error cases (when no context is set) as shown in the test results - achieving 15.3-18.7% speedup when
_temporal_context()
needs to raise the "Not in Nexus operation context" error. This makes sense because these are likely the most common code paths where the function is called to validate context existence.The
_try_temporal_context()
function remains unchanged to preserve the existing API for other callers who need the optional return behavior.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_temporal_context-mgib5dhm
and push.