python - Using builtin __import__() in normal cases -
here checked performance of __import__()
in [9]: %%timeit ...: math = __import__('math') ...: sqrt = math.sqrt ...: sqrt(7894561230) ...: slowest run took 11.16 times longer fastest. mean intermediate result being cached. 1000000 loops, best of 3: 534 ns per loop in [10]: %%timeit ...: math import sqrt ...: sqrt(7894561230) ...: ...: slowest run took 10.23 times longer fastest. mean intermediate result being cached. 1000000 loops, best of 3: 979 ns per loop
builtin __import__
module seems faster traditional way import,
so can used in code have used it, or there major harm in doing this, __import__
doc doesn't state harm in doing this.
but states
direct use of
__import__()
rare, except in cases want import module name known @ runtime.
so question can used in normal cases too. or there disadvantage of ?
here small "benchmark". let's define 2 functions:
def f1(): import sys def f2(): sys = __import__('sys')
bytecode comparison:
>>> dis.dis(f1) 5 0 load_const 1 (0) 2 load_const 0 (none) 4 import_name 0 (sys) 6 store_fast 0 (sys) 8 load_const 0 (none) 10 return_value >>> dis.dis(f2) 8 0 load_global 0 (__import__) 2 load_const 1 ('sys') 4 call_function 1 6 store_fast 0 (sys) 8 load_const 0 (none) 10 return_value
the generated bytecodes have same number of instructions, different. timing?
>>> timeit.timeit(f1) 0.4096750088112782 >>> timeit.timeit(f2) 0.474958091968411
it turns out __import__
way slower. in addition, far less readable classical import
statement.
conclusion: stick import
.
now bit of interpretation...
i suppose calling __import__
slower executing import
statement, because bytecode generated latter optimised.
take @ instructions: bytecode __import__
other function call, call_function
instruction. on other hand, import
statement results in import_name
instruction, definetely looks dedicated imports, , executed in optimised way interpreter.
as matter of fact, third instruction true difference between 2 bytecodes. difference between 2 functions lies in difference between import_name
, call_function
.
Comments
Post a Comment