跟进这个答案: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倍。
为什么呢?
getattr(foo, "bar")
往往比foo.bar
慢(在我的机器上慢了约2倍),我认为这是因为它需要在运行时做更多的工作,而不是在编译字节码时,所以你要为检查两次付出超过双倍的代价。 - Ben Kraft