[Python] improving speed of Python module import

Discussão em 'Python' iniciado por Stack, Agosto 6, 2025.

  1. Stack

    Stack Membro Participativo

    Questions about speeding up importing of Python modules have been asked (Speeding up the python "import" loader and Python -- Speed Up Imports?) but without specific examples.

    I have a Python script that loads a 3-D image stack from disk, smooths it, and displays it as a movie. I call this script from the system command prompt when I want to quickly view my data. I'm OK with the 700 ms it takes to smooth the data as this is comparable to MATLAB, but it takes an additional 650 ms to import modules.

    These are the modules I import:

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    import scipy.ndimage
    import scipy.signal
    import sys
    import os


    The slowest imports are:

    matplotlib.pyplot [300ms]
    numpy [110ms]
    scipy.signal [200ms]


    I have experimented with using from, but this isn't faster. Since Matplotlib is the main culprit and it's got a reputation for slow screen updates, I looked for alternatives. One is PyQtGraph, but that takes 550 ms to import.

    One obvious solution is to call my function from an interactive Python session rather than the system command prompt. This is fine but it's too MATLAB-like, I'd prefer the elegance of having my function available from the system prompt.

    I'm looking for a simple solution portable between Mac and Linux.

    Continue reading...

Compartilhe esta Página