⚡️ Speed up method GlobalMercator.PixelsToMeters by 60%
#14
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.
📄 60% (0.60x) speedup for
GlobalMercator.PixelsToMetersinopendm/tiles/gdal2tiles.py⏱️ Runtime :
706 microseconds→441 microseconds(best of420runs)📝 Explanation and details
The optimization adds resolution caching to the
GlobalMercatorclass, achieving a 59% speedup by eliminating redundant mathematical calculations.What was optimized:
_resolution_cachedictionary to store computed resolution values by zoom levelPixelsToMetersto check the cache before callingResolution()Why this works:
In typical tile processing workflows, the same zoom levels are used repeatedly across many pixel conversions. The original code called
Resolution()for everyPixelsToMeters()call, performing the expensive divisionself.initialResolution / (2**zoom)each time. The profiler shows this accounts for 78.5% ofPixelsToMetersexecution time.The cache eliminates this redundancy - after the first call for a given zoom level, subsequent calls skip the mathematical computation entirely. The profiler confirms that
Resolution()calls dropped from 2,099 to just 614 (only 41 unique zoom levels were encountered), while cache lookups are much faster than division operations.Best performance gains occur when:
The optimization maintains identical functionality while providing significant speedup for the common use case of processing multiple tiles at consistent zoom levels.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-GlobalMercator.PixelsToMeters-mh4irajaand push.