brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python -X importtime shows which import makes a script start slowly

Python
~/tips/tip-python-importtime-slow-startup

python -X importtime -c 'import asyncio' 2> imports.txt

Prints how long each imported module took, to find the import that slows down startup.

A command-line tool that needs a second to say anything is annoying, and often the time goes into imports, not into the work. Python can show where.

python -X importtime -c 'import asyncio' 2> imports.txt
sort -t'|' -k2 -n imports.txt | tail -n 5

The option prints one line per imported module to stderr, with a self time and a cumulative time in microseconds. Cumulative includes everything that module imported on its own. Self time leaves those out, so the biggest self time is the module that is slow itself.

Because the output goes to stderr, redirect it with 2> if you want to sort it. The table is easy to read as it is, too, since nested imports are indented.

There are two ways to turn it on. The environment variable PYTHONPROFILEIMPORTTIME=1 does the same without touching the command line, which helps when Python is started by another program.

The caveat from the docs: the output may be broken in multi-threaded applications. The option exists since Python 3.7, and since 3.14 the value 2 also lists modules that were already loaded, marked as cached. A fix for a slow import is usually to import inside the function that needs it.

Further reading: Python command line and environment

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link