Skip to content

Commit

Permalink
⚡️ Speed up function get_stack_sampler by 28%
Browse files Browse the repository at this point in the history
To optimize the given Python program for better performance, we can focus on reducing redundant operations and streamlining the logic. The `get_stack_sampler` function checks if the `stack_sampler` attribute exists in `thread_locals` and creates a `StackSampler` instance if it does not. This code is already relatively straightforward, but we can make a small improvement to slightly optimize its performance.

First, ensure that accessing the attribute and setting it is done as quickly as possible by minimizing the number of lookups. Python attribute access can be somewhat costly, so we'll reduce the number of attribute lookups slightly. Instead of using `hasattr` and `setattr` separately, we can use a single `try/except` block to handle it.

Here's the optimized version of the `get_stack_sampler` function.



This optimization minimizes attribute lookups by using a try/except block. If the `stack_sampler` attribute is not found, the exception is caught, and we create the `StackSampler` instance and set the attribute in one go.

This should slightly improve the performance of the function by reducing the overhead associated with multiple attribute lookups and method calls.
  • Loading branch information
codeflash-ai[bot] authored Jan 27, 2025
1 parent 65711d6 commit 92be613
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions pyinstrument/stack_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,9 +274,13 @@ def get_stack_sampler() -> StackSampler:
"""
Gets the stack sampler for the current thread, creating it if necessary
"""
if not hasattr(thread_locals, "stack_sampler"):
thread_locals.stack_sampler = StackSampler()
return thread_locals.stack_sampler
try:
return thread_locals.stack_sampler
except AttributeError:
# Attribute 'stack_sampler' doesn't exist in thread_locals, create it
stack_sampler = StackSampler()
thread_locals.stack_sampler = stack_sampler
return stack_sampler


def build_call_stack(frame: types.FrameType | None, event: str, arg: Any) -> list[str]:
Expand Down

0 comments on commit 92be613

Please sign in to comment.