Python 2.7:导入性能 [英] Python 2.7: import performance

查看:45
本文介绍了Python 2.7:导入性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在通过以下方式导入一堆分散在文件系统中的 .py 文件:

currently, I am importing bunch of .py files scattered across the file system via:

def do_import(name):
    import imp

    fp, pathname, description = imp.find_module(name)
    with fp:
        return imp.load_module(name, fp, pathname, description)

known_py_files = ['workingDir/import_one.py', 'anotherDir/import_two.py'] # and so forth
for py_file in known_py_files:
    do_import(py_file)

当我按如下方式对 .py 文件进行计时时,它们的数量级为 e-5 和 e-6.

when I've timed the .py files as such below, they are in the magnitude of e-5 and e-6.

import_one.py

import_one.py

import time

import_stime = time.time()
import_dur = time.time() - import_stime
print import_dur

然而,对 do_import() 的调用量级为 e-3.我猜是因为导入它的开销.

However, the call to do_import() is in the magnitude of e-3. I am guessing because of the overhead of importing it.

这对我来说是个问题,因为我连续导入了大量文件,而且导入的时间加起来.

This is a problematic for me because im importing lots of files serially and the time to import adds up.

有没有比上面提到的方法更快的导入方法?

Is there a faster way to import than the approach mentioned above?

推荐答案

如果所有文件都在一个目录下,可以在嵌套目录的每一级创建一个 __init__.py 空文件, 并导入根目录的名称,如下例中的import root:

If all of the files are under one directory, you can create an __init__.py empty file in each level of the nested directory, and import the name of the root directory, like import root in the following example:

/ root
    - __init__.py
    / workingDir
        - __init__.py
        - import_one.py
    / anotherDir
        - __init__.py
        - import_two.py

该结构称为包".

这篇关于Python 2.7:导入性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆