【发布时间】:2017-09-12 12:03:10
【问题描述】:
作为Using builtin __import__() in normal cases 问题的后续,我进行了一些测试,结果令人惊讶。
我在这里比较经典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
【问题讨论】:
-
我假设内置模块可能被提前缓存在某处。
-
@cᴏʟᴅsᴘᴇᴇᴅ 我不想放弃线索并影响潜在的回答者,但是......是的,我认为这是相关的。
标签: python performance python-import