为什么突然导入与之前完全相同的 Python 模块变得如此缓慢?

huangapple go评论58阅读模式
英文:

Why, suddenly, importing the exact same python module as before became so slow?

问题

我正在运行一个调用本地模块(使用import导入)的Python脚本,但是在过去几天变得非常慢。

我找不到它变得如此缓慢的原因,无论是在其他Github帖子还是在Google上,这就是为什么我发帖的原因。

提供代码可能不会有太大帮助,但以下是引发问题的导入部分:

import latplan

其中latplan

但是再次强调,以前这个导入一点问题都没有...

英文:

I am running a python script that calls local modules (with import), and since few days it became so slow.

I could not find the reason why it is so, neither on other Github posts or Google, that's why I am posting this.

Providing code won't be of much help, but here is the import that poses a problem:

import latplan 

where latplan is this library

But again, this import did not pose any problem at all before...

答案1

得分: 2

import 语句在 Python 中可能非常慢,因为它们允许执行任意代码作为副作用;它们不仅仅是寻找 classdef 关键字。

现在,就像任何性能问题一样,如果没有进行分析,很难猜测到底是什么让它变得如此缓慢。幸运的是,有一个内置的、专门用于导入时间的分析器:

python -X importtime -c "import latplant"

我建议使用 tuna 来可视化报告。

英文:

import statements can be very slow in Python because they are allowed to execute arbitrary code as side effects; they don't just scoot for class and def keywords.

Now, as with any performance issue, it's hard to guess what exactly is taking so long without profiling. Luckily there's a builtin, specialised profiler for import time:

python -X importtime -c "import latplant"

I recommend using tuna to visualise the reports.

huangapple
  • 本文由 发表于 2023年2月18日 18:40:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492770.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定