⚡️ Speed up function calculate_video_file_stride by 33%
#623
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.
📄 33% (0.33x) speedup for
calculate_video_file_strideininference/core/interfaces/camera/video_source.py⏱️ Runtime :
588 microseconds→442 microseconds(best of262runs)📝 Explanation and details
The optimized code achieves a 33% speedup through several key micro-optimizations:
1. Consolidated conditional checks: Combined the four separate
ifstatements checking forNoneand negative values into a single compound condition usingor. This reduces branching overhead and enables faster early exit when invalid inputs are detected.2. Eliminated unnecessary
max()calls:max(int(true_stride), 1)with direct conditional logic (if int_stride < 1: int_stride = 1)max(true_stride - integer_stride, 0)since the subtraction can never be negative wheninteger_stride = int(true_stride)3. Optimized random number generation: Added a
miss_prob > 0check before callingrandom.random(). This avoids expensive RNG calls in common cases where the probability is exactly 0 (whenactual_fps / desired_fpsis a whole number), which happens frequently with typical video frame rates.4. Reduced function call overhead: Direct assignment of
int(true_stride)instead of wrapping it inmax()eliminates one function call per execution.The optimizations are particularly effective for test cases involving:
miss_prob = 0These changes maintain identical behavior while reducing computational overhead in the hot path of video frame processing.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-calculate_video_file_stride-mhbqzkpvand push.