Skip to content

Commit

Permalink
perf: optimize stack fetching (#50)
Browse files Browse the repository at this point in the history
  • Loading branch information
taobojlen authored Jan 26, 2025
1 parent 6aa6113 commit ea88ffd
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 5 deletions.
8 changes: 5 additions & 3 deletions src/zeal/listeners.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,8 @@ def _alert(
if is_allowlisted:
return

final_caller = get_caller()
stack = get_stack()
final_caller = get_caller(stack)
if should_include_all_callers:
message = f"{message} with calls:\n"
for i, caller in enumerate(calls):
Expand Down Expand Up @@ -157,9 +158,10 @@ def notify(
context = _nplusone_context.get()
if not context.enabled:
return
caller = get_caller()
stack = get_stack()
caller = get_caller(stack)
key = (model, field, f"{caller.filename}:{caller.lineno}")
context.calls[key].append(get_stack())
context.calls[key].append(stack)
count = len(context.calls[key])
if count >= self._threshold and instance_key not in context.ignored:
message = f"N+1 detected on {model._meta.app_label}.{model.__name__}.{field}"
Expand Down
4 changes: 2 additions & 2 deletions src/zeal/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@ def get_stack() -> list[inspect.FrameInfo]:
]


def get_caller() -> inspect.FrameInfo:
def get_caller(stack: list[inspect.FrameInfo]) -> inspect.FrameInfo:
"""
Returns the filename and line number of the current caller,
excluding any code in site-packages or zeal.
"""
return next(frame for frame in get_stack())
return next(frame for frame in stack)


def is_single_query(query: Query):
Expand Down

0 comments on commit ea88ffd

Please sign in to comment.