As a followup to the question Using builtin __import__() in normal cases, I lead a few tests, and came across surprising results.
I am here comparing the execution time of a classical import statement, and a call to the __import__ built-in function.
For this purpose, I use the following script in interactive mode:
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 ">"))
As in the linked question, here is the comparison when importing sys, along with some other standard modules:
>>> 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)
So far so good, import is faster than __import__().
This makes sense to me, because as I wrote in the linked post, I find it logical that the IMPORT_NAME instruction is optimized in comparison with CALL_FUNCTION, when the latter results in a call to __import__.
But when it comes to less standard modules, the results reverse:
>>> 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)
What is the reason behind this difference in the execution times?
What is the actual reason why the import statement is faster on standard modules?
On the other hand, why is the __import__ function faster with other modules?
Tests lead with Python 3.6