温馨提示×

ubuntu python慢怎优化

小樊
34
2026-10-16 03:23:26
栏目: 编程语言

在 Ubuntu 上 Python 运行慢,常见原因和优化方向如下,按“见效快 → 根本优化”排序:


一、先确认慢在哪里(不要盲目优化)

python -m cProfile your_script.py
# 或
pip install py-spy
sudo py-spy top --pid <pid>

重点看:

  • 是 CPU 密集(算法问题)
  • 还是 IO 密集(磁盘 / 网络 / 数据库)
  • 还是 Python 本身太慢(解释器限制)

二、环境层面优化(最简单)

1. 用更快的 Python 解释器

Ubuntu 默认 python3 通常是 CPython,可换:

  • PyPy(数值 / 循环多时明显快)
sudo apt install pypy3
pypy3 your_script.py

2. 使用虚拟环境 + 正确版本

sudo apt install python3.11
python3.11 -m venv venv
source venv/bin/activate

Ubuntu 20.04/22.04 自带 Python 可能较旧

3. 关掉不必要的后台

top
htop

确认不是内存不足导致 swap:

free -h
swapon --show

三、代码层面优化(最有效)

1. 避免慢写法

❌ 慢:

result = []
for i in range(1000000):
    result.append(i*2)

✅ 快:

result = [i*2 for i in range(1000000)]
# 或
result = list(map(lambda i: i*2, range(1000000)))

2. 用 NumPy / Pandas(数值计算)

pip install numpy pandas

向量化比 for 循环快 10–100 倍

3. 多进程(CPU 密集)

from multiprocessing import Pool

with Pool(8) as p:
    p.map(func, data)

4. 异步(IO 密集)

import asyncio

四、依赖 & 编译优化

1. 安装带编译加速的包

pip install --upgrade pip
pip install numpy --no-binary :all:

2. 使用 UV(极快 Python 包管理器)

curl -LsSf https://astral.sh/uv/install.sh | sh
uv venv
uv pip install numpy

五、系统级(服务器场景)

  • 使用 SSD
  • 增加 内存(避免 swap)
  • 设置 CPU 性能模式:
sudo apt install cpufrequtils
sudo cpufreq-set -g performance

六、如果你能告诉我:

  • Python 版本
  • 是脚本 / Web / 爬虫 / 数据分析?
  • CPU 还是 IO 慢?

我可以给你针对性优化方案(甚至直接改代码)。

0 踩