记录导入模块所用的时间

Ziz*_*212 1 python import python-import

有关背景信息:去这里

我有一个非常大的模块,可以从互联网、其他内置脚本等中获取内容。根据网络速度、内存以及编译列表等因素,导入时间可以在 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)))
Run Code Online (Sandbox Code Playgroud)

当我运行这个:

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

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

>>> import tms
Loading Module. This may take up to 60 seconds.
Time taken: 31.49 seconds
Run Code Online (Sandbox Code Playgroud)

这是我的问题。这是我必须在导入模块之前定义的函数。我需要能够做的是让我的模块能够在启动时做到这一点。我看过这个问题,但它是相同的概念。有没有人有任何想法?

Frx*_*rem 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
Run Code Online (Sandbox Code Playgroud)