⚡️ Speed up method VideoSourcesManager.all_sources_ended by 25%
#799
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.
📄 25% (0.25x) speedup for
VideoSourcesManager.all_sources_endedininference/core/interfaces/camera/utils.py⏱️ Runtime :
25.4 microseconds→20.4 microseconds(best of52runs)📝 Explanation and details
The optimization caches the length of
video_sources.all_sourcesduring initialization instead of computing it on every call toall_sources_ended(). This simple change delivers a 24% speedup by eliminating redundantlen()calls.Key optimization:
self._all_sources_len = len(self._video_sources.all_sources)in__init__len(self._video_sources.all_sources)toself._all_sources_lenWhy this works:
The
len()function has overhead when called repeatedly, even on simple containers. By pre-computing the length once during initialization, each call toall_sources_ended()saves the cost of:self._video_sources.all_sources)len())all_sourcesis not a simple list/tuplePerformance characteristics:
Assumptions:
This optimization assumes
video_sources.all_sourcesremains static after VideoSourcesManager initialization, which is typical for video source management where the set of cameras/streams is configured upfront. If sources can be dynamically added/removed, the cache would need invalidation logic.The optimization is particularly valuable if
all_sources_ended()is called frequently in monitoring loops or status checks, which is common in video processing pipelines.✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-VideoSourcesManager.all_sources_ended-miqvkdp1and push.