⚡️ Speed up method TimeSeries_TimedeltaFormatter.format_timedelta_ticks by 20%
#98
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.
📄 20% (0.20x) speedup for
TimeSeries_TimedeltaFormatter.format_timedelta_ticksinpandas/plotting/_matplotlib/converter.py⏱️ Runtime :
23.9 microseconds→20.0 microseconds(best of31runs)📝 Explanation and details
The optimized code achieves a 19% speedup through two key optimizations:
1. Conditional Decimals Calculation: The original code always computes
decimals = int(ns * 10 ** (n_decimals - 9))regardless of whether decimals are needed. The optimized version moves this calculation inside theif n_decimals > 0:block, avoiding unnecessary computation whenn_decimalsis 0.2. Integer Division Instead of Multiplication: When decimals are needed, the optimized code uses
decimals = ns // (10 ** (9 - n_decimals))instead ofint(ns * 10 ** (n_decimals - 9)). This replaces floating-point multiplication followed by int conversion with direct integer division, which is more efficient.3. Reduced String Operations: The optimized version constructs the time string only once per branch - either with or without decimals - rather than always building the base string and conditionally appending decimals with
+=.The line profiler shows the original decimals calculation took 16% of total time (6996ns out of 43696ns), while the optimized conditional approach significantly reduces this overhead. The test cases demonstrate this optimization is particularly effective for scenarios with
n_decimals = 0(like basic time formatting) and high-volume tick generation, where avoiding unnecessary decimal calculations provides consistent performance gains.✅ Correctness verification report:
⚙️ Existing Unit Tests and Runtime
plotting/test_converter.py::TestTimeDeltaConverter.test_format_timedelta_ticks🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-TimeSeries_TimedeltaFormatter.format_timedelta_ticks-mhbqwnhxand push.