开发者

Efficiency of imports in Python

I have a module with many functions:

Module One

def a():
 ...
def b():
 ...
def c():
 ....

Now, from a different module, I need to import only function b. For that purpose, i am using the syntax:

from One import b

My question - beside from namespace considerations, is there any positive effect on the time开发者_如何学JAVA complexity of my program if I use the import stated above rather than import One , since that way I only import the necessary functions (for the sake of the example I only used 3 function in module One, but I have many more)


No. The full module must be completely run (the first time) to be certain that the name will even exist within it regardless.


Let's find out by benchmarking. Start with the script:

#!/usr/bin/python
for i in xrange(100000):
    print "def foo%d(): pass\n" % i

Which generates a large Python program. We save it to foo.py.

Program import.py just does a import foo, (four repeats):

# time python import.py

7.83s user 0.55s system 99% cpu 8.381 total
1.52s user 0.11s system 99% cpu 1.630 total
1.54s user 0.09s system 100% cpu 1.626 total
1.48s user 0.15s system 100% cpu 1.623 total

The second (and subsequent) executions are faster, because Python creases a file foo.pyc after importing foo the first time, which contains the results of parsing foo.py. This speeds up all subsequent imports of the module.

Program fromimport.py does a from foo import foo1, (four repeats):

# time python fromimport.py

7.81s user 0.44s system 99% cpu 8.253 total
1.48s user 0.15s system 100% cpu 1.626 total
1.52s user 0.11s system 99% cpu 1.631 total
1.49s user 0.14s system 100% cpu 1.630 total

These times are very similar to the previous program (once again, the first time being slower because Python needs to parse the foo.py), which confirms the statements of other answers already provided that there is no significant performance difference between import foo and from foo import foo1 in common scenarios.

As others have noted, this is because Python needs to parse/run the entire file, even if only a small part of it is actually used by the caller.


The full module has to be loaded, imagine this:

b = 1
def a():
    return b

Now in our second file:

from somemodule import a

print a()    

uh oh

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜