⚡️ Speed up function output_to_target by 35%
#13
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.
📄 35% (0.35x) speedup for
output_to_targetinultralytics/utils/plotting.py⏱️ Runtime :
7.39 milliseconds→5.48 milliseconds(best of63runs)📝 Explanation and details
The optimization focuses on the
xyxy2xywhfunction, which converts bounding box coordinates from (x1, y1, x2, y2) format to (x, y, width, height) format. The key improvement replaces four individual element-wise assignments with two vectorized slice operations.What was optimized:
y[..., 0] = ...,y[..., 1] = ..., etc.), the optimized version uses slice assignments (y[..., :2] = ...,y[..., 2:] = ...) that operate on multiple elements simultaneously.xyandwhvariables, reducing redundant indexing operations.Why this leads to speedup:
Performance impact in context:
The
xyxy2xywhfunction is called fromoutput_to_target, which is used in YOLO model validation for plotting predictions (as shown in the function references). During validation, this function processes detection results for visualization, and the 34% speedup directly reduces the time spent converting bounding box formats. The test results show consistent improvements across all scenarios, with particularly strong gains (39-51%) for large-scale cases with many batches or detections, making validation plotting significantly faster.Test case benefits:
The optimization performs well across all test scenarios, with especially strong improvements for large-scale cases (many batches: 51% faster, large detections: 28-40% faster), indicating the vectorized approach scales better than individual assignments.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-output_to_target-mi8ewrk0and push.