作为问题的后续使用内置的__import__()正常情况下 https://stackoverflow.com/q/46173417/7051394,我进行了一些测试,并得到了令人惊讶的结果。
我在这里比较经典的执行时间import
声明,并呼吁__import__
内置功能。
为此,我在交互模式下使用以下脚本:
import timeit
def test(module):
t1 = timeit.timeit("import {}".format(module))
t2 = timeit.timeit("{0} = __import__('{0}')".format(module))
print("import statement: ", t1)
print("__import__ function:", t2)
print("t(statement) {} t(function)".format("<" if t1 < t2 else ">"))
正如在链接的问题中一样,这是导入时的比较sys
,以及其他一些标准模块:
>>> test('sys')
import statement: 0.319865173171288
__import__ function: 0.38428380458522987
t(statement) < t(function)
>>> test('math')
import statement: 0.10262547545597034
__import__ function: 0.16307580163101054
t(statement) < t(function)
>>> test('os')
import statement: 0.10251490255312312
__import__ function: 0.16240755669640627
t(statement) < t(function)
>>> test('threading')
import statement: 0.11349136644972191
__import__ function: 0.1673617034957573
t(statement) < t(function)
到目前为止,一切都很好,import
比__import__()
。
这对我来说很有意义,因为正如我在链接的帖子中所写的那样,我发现合乎逻辑的是IMPORT_NAME
与相比,指令被优化CALL_FUNCTION
,当后者导致调用__import__
.
但当涉及到不太标准的模块时,结果就会相反:
>>> test('numpy')
import statement: 0.18907936340054476
__import__ function: 0.15840019037769792
t(statement) > t(function)
>>> test('tkinter')
import statement: 0.3798560809537861
__import__ function: 0.15899962771786136
t(statement) > t(function)
>>> test("pygame")
import statement: 0.6624641952621317
__import__ function: 0.16268579177259568
t(statement) > t(function)
执行时间差异背后的原因是什么?
其真实原因是什么import
标准模块上的语句更快?
另一方面,为什么__import__
与其他模块一起运行速度更快吗?
使用 Python 3.6 进行测试