I want to know how much time an import takes for both built-in as well as user defined modules.
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Starting from Python3.7 releaese, new
-X importtime
option is available. To measure import time, just simply execute your script with that option, e.g.python -X importtime my_script.py
.For reference:
One way to profile imports is to use the profile_imports module used in bzr source code:
Besides giving you timing for imports, this also estimates time to compile regex, which is often a significant cause for slowdown in imports.
You can test this runnning
However, what would this help you? Importing only happens once and will almost never be a bottle neck. Importing the same module over and over will not run significantly slower than importing it once, since Python tracks which modules have already been imported.
What are you actually trying to achieve?
Tested on Windows in Python 2.4 - you can try it yourself.
So there is a big difference between cached modules and those being brought in from scratch. To illustrate, we can reload the module:
Use cProfile:
I ran into this issue profiling a large legacy application with a multi-second startup time. It's relatively simple to replace the builtin importer with something that does some profiling. Below is a hacky way of showing approximately how long each module takes to execute:
Running on a simple example, here's how it looks on importing scipy.stats: