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

5

跟进这个答案:https://dev59.com/UG445IYBdhLWcg3wDV8P#17366561

在我的MacBook Pro 2015上(2.8 GHz英特尔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._getframe()比inspect.currentframe()快4倍。

为什么呢?

1个回答

6

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

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

该函数除了调用sys._getframe外还调用了hasattr,因此它肯定会更慢。 hasattr的作用是尝试获取属性,并在失败时捕获AttributeError异常。由于再次存在并检索了_getframe属性,因此增加了额外的开销。

2
此外,getattr(foo, "bar") 往往比 foo.bar 慢(在我的机器上慢了约2倍),我认为这是因为它需要在运行时做更多的工作,而不是在编译字节码时,所以你要为检查两次付出超过双倍的代价。 - Ben Kraft

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接