跟进这个答案:/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 倍。
怎么会?
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检索,从而增加了开销。