⚡️ Speed up function prompt_text by 131%
#24
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.
📄 131% (1.31x) speedup for
prompt_textinframework/py/flwr/cli/utils.py⏱️ Runtime :
6.40 milliseconds→2.77 milliseconds(best of143runs)📝 Explanation and details
The optimization moves the expensive
typer.style()calls outside thewhile Trueloop to avoid repeated computation. In the original code, every time the user enters invalid input, both the prompt styling and error message styling are recalculated. The line profiler shows thattyper.style()calls consumed 31.5% and 54.8% of the total runtime respectively.Key changes:
styled_promptandstyled_erroronce before the loopWhy this is faster:
typer.style()performs string formatting and ANSI escape code generation internally, which involves multiple string operations and color calculations. By computing these styled strings once upfront, we eliminate this overhead on every loop iteration when users provide invalid input.Test case performance:
This optimization is most beneficial for test cases with multiple invalid attempts before valid input, such as:
test_prompt_text_large_scale()- 999 invalid inputs before valid onetest_large_scale_many_attempts()- 100 attempts before valid inputtest_prompt_text_predicate_always_false()- Multiple rejections by predicateThe 131% speedup demonstrates significant savings when the validation loop runs multiple iterations, as styling overhead is eliminated from the hot path.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-prompt_text-mh17i9dqand push.