Conversation
11d9a13 to
b3056d4
Compare
Co-authored-by: Yvonne Fröhlich <94163266+yvonnefroehlich@users.noreply.github.com>
michaelgrund
approved these changes
May 21, 2024
__getitem__ special method to avoid calling API function GMT_Get_Enum repeatedly
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
The
__getitem__method is a magic method that makes theSessionclass behave like a dictionary so that we can access the value of GMT constants likeself["GMT_IS_DATASET"].self["GMT_IS_DATSET"]is translated to the statementself.__get_item__("GMT_IS_DATASET"), which then calls the GMT C API functionGMT_Get_Enum.Currently, the
__getitem__method calls theGMT_Get_Enumfunction everytime a constant is accessed, so it's not efficient. To check how many times constants are accessed, I've added a print statement in the__getitem__method.As you can see, even in the simplest script,
GMT_PAD_DEFAULTandGMT_SESSION_EXTERNALare called 7 times each.This PR refactors the
__getitem__method by storing the values of GMT constants in theGMT_CONSTANTSdictionary. When a constant is accessed for the first time,GMT_Get_Enumis called to the get its value and the value is stored inGMT_CONSTANTS. When the constant is accessed later, it will get the value from theGMT_CONSTANTSdictionary directly.Below is a simple benchmark showing the performance improvement.
Main branch:
This branch:
From the benchmark result, we can conclude that:
GMT_CONSTANTSdictionary takes about 66 ns, which is 10x fasterThis PR doesn't affect our "Benchmarks" workflow, because in our tests,
__get_item__is usually called a few times (like 10), so the execution time may decrease by only 10 ms, which has minor effects on the "Benchmarks" results.