Python 为什么inspect.currentframe比sys慢_获取帧?

Python 为什么inspect.currentframe比sys慢_获取帧?,python,Python,就这一答复采取后续行动: 在我的macbook pro 2015(2.8 GHz Intel Core i7)和python 3.6上,我得到: python3 -m timeit -s 'import inspect' 'inspect.currentframe().f_code.co_name' >>> 1000000 loops, best of 3: 0.428 usec per loop python3 -m timeit -s 'import sys' 'sys.

就这一答复采取后续行动:

在我的macbook pro 2015(2.8 GHz Intel Core i7)和python 3.6上,我得到:

python3 -m timeit -s 'import inspect' 'inspect.currentframe().f_code.co_name'
>>> 1000000 loops, best of 3: 0.428 usec per loop

python3 -m timeit -s 'import sys' 'sys._getframe().f_code.co_name'

>>> 10000000 loops, best of 3: 0.114 usec per loop
使用sys.\u getframe()比inspect.currentframe()快4倍


为什么

假设问题是关于CPython的,您可以看到
inspect.currentframe的实现:

该函数除了调用
sys.\u getframe
之外,还调用了
hasattr
,因此它的速度必须较慢

hasattr
通过尝试获取属性并捕获
AttributeError
异常(如果失败)来工作。
\u getframe
属性存在并被再次检索,从而增加了开销。

此外,
getattr(foo,“bar”)
通常比
foo.bar
慢(在我的机器上是~2x),我相信这是因为它在运行时需要做更多的工作,而不是在编译字节码时,所以您需要支付两倍以上的检查费用。
def currentframe():
    """Return the frame of the caller or None if this is not possible."""
    return sys._getframe(1) if hasattr(sys, "_getframe") else None