繁体   English   中英

Python - 加速进口?

[英]Python — Speed Up Imports?

我有10000s自定义(编译为'.so')模块,我想在python使用。 模块的使用将是相应的(模块一个接一个地使用;不是同时使用)。

通常,代码看起来像这样:

# list with all the paths to all modules  
listPathsToModules = [.....]
# loop through the list of all modules 
for i in xrange(listPathsToModules):
    # get the path to the currently processed module 
    pathToModule = listPathsToModules[i]
    # import the module
    import pathToModule
    # run a function in 'pathToModule' and get the results
    pathToModule.MyFunction( arg1, arg2, arg3 )

运行这个,这是我发现的:

平均 导入一个模块所需的时间: 0.0024625 [sec]

平均 运行模块功能所需的时间: 1.63727e-05 [sec]

这意味着, it takes x100 more time to import the module than to run a function that is in it!

有什么办法可以加快在python加载模块所需的时间吗? 鉴于需要加载和运行许多(假设10,000个)模块,您将采取哪些步骤来优化这种情况?

我首先会质疑import是否真的是你想要用来访问数千个代码片段的技术 - 完整的导入过程非常昂贵,加载(非共享)动态模块也不是特别便宜。

其次,你清楚地写出来的代码并不是你真正在做的。 import语句在运行时不接受字符串,您必须直接使用importlib.import_module()或调用__import__()

最后,优化它的第一步是确保sys.path上的第一个目录是包含所有这些文件的目录。 您可能还希望使用-vv标志运行Python以拨打导入尝试的详细程度。 请注意,如果您正在进行多次进口,这将会非常嘈杂。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM