⚡️ Speed up function remove_colorstr by 11%
#10
+3
−2
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.
📄 11% (0.11x) speedup for
remove_colorstrinultralytics/utils/__init__.py⏱️ Runtime :
516 microseconds→465 microseconds(best of250runs)📝 Explanation and details
The optimization moves the regex compilation from inside the function to module level, eliminating redundant regex compilation on every function call.
Key Changes:
_ANSI_ESCAPE_REis compiled once at module import time instead of being recompiled in every function callWhy This Optimization Works:
The original code compiled the same regex pattern
r"\x1B\[[0-9;]*[A-Za-z]"on every function invocation, which is expensive. The line profiler shows that 40.5% of the original function's time was spent onre.compile(). By moving this compilation to module level, we eliminate this overhead entirely.Performance Impact:
Real-World Benefits:
Based on the function reference,
remove_colorstr()is called from hyperparameter tuning code where it processes log headers that likely contain colored terminal output. Since tuning involves many iterations with logging, this 11% speedup in string processing can accumulate to meaningful time savings during long optimization runs. The function appears to be in a hot path where logging occurs frequently, making this micro-optimization worthwhile.The optimization is particularly effective for workloads with repeated calls to remove ANSI codes from strings, which is common in CLI tools and logging systems where colored output needs to be cleaned for file storage or plain text display.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-remove_colorstr-mi8cu2ouand push.