⚡️ Speed up function showhelp by 57%
#84
Open
+27
−11
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.
📄 57% (0.57x) speedup for
showhelpinsrc/_pytest/helpconfig.py⏱️ Runtime :
4.59 milliseconds→2.92 milliseconds(best of250runs)📝 Explanation and details
The optimizations achieve a 57% speedup by targeting two key performance bottlenecks:
1. TerminalWriter.write() optimization:
msg.rsplit("\n", 1)[-1]calls when no newlines are present"\n" in msg) before splitting, eliminating ~30% of unnecessary string operations based on the profiler data showing reduced time in the rsplit linewrite()is called frequently during help output generation (34 hits in profiling), this micro-optimization compounds significantly2. showhelp() caching optimization:
wrap_cachedictionary to cachetextwrap.wrap()results based on(help_text, width)tuplestextwrap.wrap()consumed 82.5% of total execution time in the original code. Many ini options have identical help text or are processed with the same width parameters, making caching highly effectiveFunction context impact:
Based on
function_references,showhelp()is called frompytest_cmdline_main()when users runpytest --help. This is a user-facing command that benefits significantly from faster response times, especially in environments with many configured ini options.Test case performance:
The optimizations show the most benefit in large-scale scenarios - the test with many large help texts shows a 573% speedup (2.13ms → 316μs), demonstrating that caching becomes increasingly effective as the number of similar text-wrapping operations grows. Basic cases show modest 2-9% overhead due to cache setup, but this is quickly offset in real-world usage with multiple ini options.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-showhelp-mi9uulsuand push.