为什么inspect.currentframe比sys.currentframe慢?_getframe?

use*_*118 5 python

跟进这个答案:/sf/answers/1215659301/

在我的 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
Run Code Online (Sandbox Code Playgroud)

使用sys._getframe() 比inspect.currentframe() 快4 倍。

怎么会?

vau*_*tah 6

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

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
Run Code Online (Sandbox Code Playgroud)

hasattr除了 之外,该函数还调用sys._getframe,因此它必须更慢。

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

  • 此外,`getattr(foo, "bar")` 通常比 `foo.bar` 慢(在我的机器上大约是 2 倍),我相信因为它必须在运行时而不是编译字节码时做更多的工作,所以你付出更多比检查两次多一倍。 (2认同)