Python 3.11 module import timer
timed_imports.py
1import sys
2import time
3from importlib import machinery
4
5
6class CustomLoader(machinery.SourceFileLoader):
7 last_end = None
8 depth = 0
9 print_depth = None
10
11 def exec_module(self, module):
12 start = time.time_ns()
13 CustomLoader.depth += 1
14 try:
15 result = super().exec_module(module)
16 finally:
17 CustomLoader.depth -= 1
18 end = time.time_ns()
19 if CustomLoader.last_end is None:
20 CustomLoader.last_end = end
21 if (
22 CustomLoader.print_depth is None
23 or CustomLoader.depth <= CustomLoader.print_depth
24 ):
25 print(
26 f"{' ' * CustomLoader.depth}{(end - start) // 10000 / 100}ms ({(end - CustomLoader.last_end) // 10000 / 100}ms local) to load {module.__name__} ",
27 )
28 CustomLoader.last_end = end
29 return result
30
31
32class CustomFinder(machinery.PathFinder):
33 @classmethod
34 def _get_spec(cls, fullname, path=None, target=None):
35 spec = super()._get_spec(fullname, path, target)
36 if spec is None:
37 return None
38 if isinstance(spec.loader, machinery.SourceFileLoader):
39 spec.loader = CustomLoader(spec.loader.name, spec.loader.path)
40 return spec
41
42
43sys.meta_path.insert(4, CustomFinder())