Python加速导入?

2024-10-01 13:44:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有10000个自定义(编译为'.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中加载模块所需的时间吗?考虑到需要加载和运行多个(假设10000个)模块,您将采取哪些步骤来优化这种情况?在


Tags: 模块thetoruninimportmodulesget
1条回答
网友
1楼 · 发布于 2024-10-01 13:44:33

我首先要问的是,import是否真的是您想要用来访问成千上万代码片段的技术-完整的导入过程相当昂贵,加载(非共享)动态模块也不是特别便宜。在

第二,你写的代码显然不是你实际在做的。import语句在运行时不接受字符串,您必须使用importlib.import_module()或直接调用__import__()。在

最后,优化的第一步是确保sys.path上的first目录包含所有这些文件。您可能还希望运行带有-vv标志的Python,以便在导入尝试时拨出详细信息。请注意,如果你做了那么多的进口,这将使噪音非常大。在

相关问题 更多 >