Skip to content

Fix excessive thread name lookups#790

Open
tdryer wants to merge 2 commits into
benfred:masterfrom
tdryer:thread-name-lookups
Open

Fix excessive thread name lookups#790
tdryer wants to merge 2 commits into
benfred:masterfrom
tdryer:thread-name-lookups

Conversation

@tdryer
Copy link
Copy Markdown

@tdryer tdryer commented Jul 29, 2025

py-spy uses a cache to minimize the overhead of looking up Python thread names during sampling. If looking up a thread name fails, the entire cache is rebuilt. However, if a failure is persistent, this causes the cache to be rebuilt during every sample (potentially more than once), creating excessive overhead.

Two cases when persistent thread name lookup failures can occur are:

  • When the threading module has not been imported
  • When a thread was created outside of the threading module, such as through _thread.start_new_thread

Fix this by modifying the cache to store a negative response (None) if the thread name is still not found after rebuilding the cache. To prevent negative responses from being lost when more than one thread name lookup fails, add a flag preventing the cache from being rebuilt more than once per sample.

One disadvantage of this approach is that in nonblocking mode, a spurious negative response can be cached for an extended duration. This happens if the thread is created during a sample and after the single allowed thread name lookup happens.

tdryer and others added 2 commits July 29, 2025 11:19
py-spy uses a cache to minimize the overhead of looking up Python thread
names during sampling. If looking up a thread name fails, the entire
cache is rebuilt. However, if a failure is persistent, this causes the
cache to be rebuilt during every sample (potentially more than once),
creating excessive overhead.

Two cases when persistent thread name lookup failures can occur are:

* When the `threading` module has not been imported
* When a thread was created outside of the `threading` module, such as
  through `_thread.start_new_thread`

Fix this by modifying the cache to store a negative response (`None`) if
the thread name is still not found after rebuilding the cache. To
prevent negative responses from being lost when more than one thread
name lookup fails, add a flag preventing the cache from being rebuilt
more than once per sample.

One disadvantage of this approach is that in nonblocking mode, a
spurious negative response can be cached for an extended duration. This
happens if the thread is created during a sample and after the single
allowed thread name lookup happens.
@benfred benfred added the enhancement New feature or request label Apr 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants