Unverified Commit cd9dcc19 authored by Andrew Stahlman's avatar Andrew Stahlman Committed by GitHub
Browse files

[Enhancement] Speed up Registry initialization (#1844)

* Speed up Registry initialization

This PR addresses https://github.com/open-mmlab/mmcv/issues/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
parent 5cded66a
......@@ -139,9 +139,12 @@ class Registry:
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]
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment