Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve performance of strawberry.lazy() with relative imports #2926

Merged
merged 5 commits into from
Jul 8, 2023
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion strawberry/lazy_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def __init__(self, module: str) -> None:
self.package = None

if module.startswith("."):
frame = inspect.stack()[2][0]
frame = inspect.currentframe().f_back.f_back
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't bother to check for nulls at every location, since this should only be accessed via .lazy() and also the previous code would've hit a bounds check in the same condition anyways

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice! we also use sys._getframe(x) in another place, would you mind trying with that and see if performs the same? 😊

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yupp! It has the same effect - actually _getframe is in C, so looks like it is even faster. Whipped up a small benchmark to look at the difference:

Screenshot 2023-07-06 at 5 34 35 PM
import time
import inspect
import sys

def run_benchmark(name, fn):
	start_time = time.time()

	for i in range(1000000):
		fn()

	end_time = time.time()
	duration = end_time - start_time

	print(f"{name} completed in {duration}s")

def main():
	run_benchmark("inspect.stack()[2]", lambda: inspect.stack()[2])
	run_benchmark("inspect.currentframe().f_back.f_back", lambda: inspect.currentframe().f_back.f_back)
	run_benchmark("sys._getframe(2)", lambda: sys._getframe(2))

main()

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

awesome! thanks for that!

# TODO: raise a nice error if frame is None
assert frame is not None
self.package = cast(str, frame.f_globals["__package__"])
Expand Down
Loading