⚡️ Speed up method EmbedMaxDct.encode by 6%
#160
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.
📄 6% (0.06x) speedup for
EmbedMaxDct.encodeininvokeai/backend/image_util/imwatermark/vendor.py⏱️ Runtime :
105 milliseconds→99.2 milliseconds(best of58runs)📝 Explanation and details
The optimized code achieves a 6% speedup through several key performance improvements in the image watermarking pipeline:
What optimizations were applied:
rows4 = row // 4 * 4andcols4 = col // 4 * 4calculations outside the channel loop to avoid redundant computationself._block,self._wmLen,self._watermarks) as local variables to reduce attribute lookup overheadnumcounter with direct calculation(i * num_blocks_col + j) % wmLen, eliminating an increment operation per blockdiffusedBlock = self.diffuse_dct_matrix(...)assignment since the method modifies blocks in-place, avoiding unnecessary variable creation and assignment overheadWhy these optimizations improve performance:
diffusedBlockvariable reduces temporary object creation in the hot pathKey performance impact:
The line profiler shows the most significant improvement in
encode_frame(from 177ms to 146ms), which processes the majority of blocks. Thediffuse_dct_matrixcall remains the bottleneck at ~80% of runtime, but the loop overhead optimizations provide measurable gains.Test case performance:
The optimizations show consistent 2-9% improvements across various scenarios, with larger images (256x256, 512x512) benefiting most due to the multiplicative effect of loop optimizations across thousands of blocks. Small images see modest gains due to lower absolute loop counts.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-EmbedMaxDct.encode-mhwxdiumand push.