在 Ubuntu 上 Python 运行慢,常见原因和优化方向如下,按“见效快 → 根本优化”排序:
python -m cProfile your_script.py
# 或
pip install py-spy
sudo py-spy top --pid <pid>
重点看:
Ubuntu 默认 python3 通常是 CPython,可换:
sudo apt install pypy3
pypy3 your_script.py
sudo apt install python3.11
python3.11 -m venv venv
source venv/bin/activate
Ubuntu 20.04/22.04 自带 Python 可能较旧
top
htop
确认不是内存不足导致 swap:
free -h
swapon --show
❌ 慢:
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)))
pip install numpy pandas
向量化比 for 循环快 10–100 倍
from multiprocessing import Pool
with Pool(8) as p:
p.map(func, data)
import asyncio
pip install --upgrade pip
pip install numpy --no-binary :all:
curl -LsSf https://astral.sh/uv/install.sh | sh
uv venv
uv pip install numpy
sudo apt install cpufrequtils
sudo cpufreq-set -g performance
我可以给你针对性优化方案(甚至直接改代码)。