Skip to content

Commit

Permalink
[Enhancement] Speed up Registry initialization (#1844)
Browse files Browse the repository at this point in the history
* Speed up Registry initialization

This PR addresses #1843.

Instead of calling inspect.stack() to read the entire stack and its
associated source files from disk, walk up the stack to get only the
specific frame that we need (see [1] for additional information).

This makes imports in downstream projects ~2.5x faster in my local dev
environment. For mmaction2, for example:

Before:

    $ python -m timeit -n1 -r1 "from mmaction.apis import init_recognizer, inference_recognizer"
    1 loop, best of 1: 1.94 sec per loop

After:

    $ python -m timeit -n1 -r1 "from mmaction.apis import init_recognizer, inference_recognizer"
    1 loop, best of 1: 754 msec per loop

[1] https://stackoverflow.com/a/42636264/895769

* Add comment with PR tag

Explain why we avoid `inspect.stack()` with link to PR
  • Loading branch information
astahlman authored Apr 14, 2022
1 parent 5cded66 commit cd9dcc1
Showing 1 changed file with 6 additions and 3 deletions.
9 changes: 6 additions & 3 deletions mmcv/utils/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,12 @@ def infer_scope():
Returns:
str: The inferred scope name.
"""
# inspect.stack() trace where this function is called, the index-2
# indicates the frame where `infer_scope()` is called
filename = inspect.getmodule(inspect.stack()[2][0]).__name__
# We access the caller using inspect.currentframe() instead of
# inspect.stack() for performance reasons. See details in PR #1844
frame = inspect.currentframe()
# get the frame where `infer_scope()` is called
infer_scope_caller = frame.f_back.f_back
filename = inspect.getmodule(infer_scope_caller).__name__
split_filename = filename.split('.')
return split_filename[0]

Expand Down

0 comments on commit cd9dcc1

Please sign in to comment.