在 Ubuntu 上优化 Python 性能,可以从系统环境、Python 版本、代码写法、并发模型、工具分析等多个层面来做。下面按实际使用场景给你一个相对完整的优化清单。
Ubuntu 自带 Python 可能较旧(如 3.8 / 3.10):
python3 --version
建议使用 Python 3.11+(性能提升明显):
sudo apt update
sudo apt install software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt install python3.11
或使用 pyenv 管理多版本:
curl https://pyenv.run | bash
pyenv install 3.12.1
pyenv global 3.12.1
✅ Python 3.11 比 3.8 快 10–25%
python3 -m venv venv
source venv/bin/activate
❌ 不推荐:
result = []
for i in range(1000000):
result.append(i * 2)
✅ 推荐:
result = [i * 2 for i in range(1000000)]
map / filter / sumitertoolscollectionsfrom collections import Counter
c = Counter(data)
❌:
s = ""
for x in lst:
s += x
✅:
s = "".join(lst)
| 场景 | 推荐 |
|---|---|
| 查找 | set / dict |
| 队列 | collections.deque |
| 大列表 | array / numpy |
✅ asyncio
import asyncio
async def main():
await asyncio.sleep(1)
asyncio.run(main())
或使用:
aiohttpasyncpg✅ 多进程
from multiprocessing import Pool
def f(x):
return x * x
with Pool() as p:
print(p.map(f, range(10)))
⚠️ 多线程 不适合 CPU 密集(GIL)
sudo apt install pypy3
pypy3 script.py
✅ 长时间运行计算代码提升明显
from numba import njit
@njit
def f(x):
return x + 1
python3 -m cProfile -s time script.py
pip install line_profiler
pip install memory_profiler
ulimit -n
ulimit -n 65535
free -h
swapon -s
| 问题 | 解决方法 |
|---|---|
| 慢循环 | numpy / numba |
| 网络慢 | asyncio |
| CPU 高 | multiprocessing |
| 内存大 | 生成器 / array |
| 启动慢 | 减少 import |
✅ Web 服务
✅ 数据处理
✅ 脚本工具
如果你愿意,可以告诉我:
我可以给你 针对性的优化方案或代码重构示例。