记录导入模块所需的时间

问题描述 投票:0回答:3

了解背景信息:前往此处

我有一个非常大的模块,它从互联网、其他内置脚本等获取内容。根据网络速度、内存、然后编译列表等因素,导入时间可能会在 25 秒到 25 秒之间变化。 90秒。我使用以下代码来跟踪模块导入所需的时间:

def importTime():
    import time
    startTime = time.time()
    import tms              # This is the name of my module
    print("Time taken {}".format(time.time() - startTime)))

当我运行这个时:

>>> importTime()
Loading Module. This may take up to 60 seconds. # This is my module output
Time taken 31.49

这就是我想要发生的事情:

>>> import tms
Loading Module. This may take up to 60 seconds.
Time taken: 31.49 seconds

这是我的问题。这是我在导入模块之前必须定义的函数。我需要做的是让我的模块能够在启动时执行此操作。我已经看过这个问题,但这是相同的概念。有人有什么想法吗?

python import python-import
3个回答
5
投票

您可以重载导入模块时调用的

__import__
函数:

import time
import __builtin__

# save the original __import__ function
original_import = __builtin__.__import__

def custom_import(name, globals=None, locals=None, fromlist=None, level=-1):
  startTime = time.time()

  # call original __import__ function
  result = original_import(name, globals, locals, fromlist, level)

  endTime = time.time()
  print('Time used to load module {}: {}'.format(name, endTime - startTime))

  # return result
  return result

# replace builtin __import__ function
__builtin__.__import__ = custom_import

2
投票

通常不希望在模块导入中进行大量工作 - 这会对文档扫描仪、IDE、单元测试框架等造成严重破坏。理想情况下,应该重写

tms
以在函数中完成其工作。但要解决您的问题,只需编写一个导入您的模块的简短模块即可。您甚至可以将其命名为
tms
并重命名原来的名称,以便其他进口商获得相同的功能(如果需要的话)。

tmsx.py

import time
startTime = time.time()
from tms import *         # This is the name of my module
print("Time taken {}".format(time.time() - startTime)))

现在只需导入 tmsx

>>> import tmsx
Loading Module. This may take up to 60 seconds.
Time taken: 31.49 seconds

0
投票

您可能想使用通用方式:

python -X importtime script.py 2>/tmp/import_module_time.log

然后分析结果

© www.soinside.com 2019 - 2024. All rights reserved.