在 Ubuntu 上优化 Python 性能,可以从系统环境、Python 版本、依赖库、代码结构、并发与部署等多个层面入手。下面按实用程度给你一个系统化清单。
sudo apt update && sudo apt upgrade -y
新内核通常对调度、I/O、内存管理有改进。
查看当前限制:
ulimit -a
提高文件描述符限制(常用于高并发):
sudo vim /etc/security/limits.conf
添加:
* soft nofile 65535
* hard nofile 65535
Ubuntu 22.04+ 默认已支持。
python3 --version
如果版本过低,使用 pyenv 安装新版本:
sudo apt install -y build-essential libssl-dev zlib1g-dev \
libncurses5-dev libgdbm-dev libnss3-dev libreadline-dev \
libsqlite3-dev libffi-dev
curl https://pyenv.run | bash
| 方案 | 说明 |
|---|---|
| CPython(默认) | 稳定 |
| PyPy | 长时间运行程序快 2–10 倍 |
| Python + C 扩展 | 性能瓶颈函数 |
安装 PyPy:
sudo apt install pypy3
python3 -m venv venv
source venv/bin/activate
pip install -U pip
pip install -r requirements.txt
或使用:
pip install poetry
✅ 快:
list, dict, set, tuple
❌ 慢:
自定义对象、嵌套循环
❌ 慢:
for i in range(len(lst)):
print(lst[i])
✅ 快:
for x in lst:
print(x)
def f():
local_print = print
for i in range(1000000):
local_print(i)
def gen():
for i in range(1000000):
yield i
| 场景 | 推荐 |
|---|---|
| 数值计算 | NumPy |
| 数据处理 | Pandas |
| 并发 | asyncio / concurrent.futures |
| 网络 | aiohttp / fastapi |
| 编译加速 | Cython / Numba |
from multiprocessing import Pool
with Pool() as p:
p.map(func, data)
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor() as executor:
executor.map(func, data)
import asyncio
async def main():
await asyncio.sleep(1)
asyncio.run(main())
python3 -m cProfile script.py
pip install memory_profiler
python3 -m memory_profiler script.py
pip install line_profiler
gunicorn -w 4 -k uvicorn.workers.UvicornWorker app:app
python3 -O script.py
如果你愿意,可以告诉我:
我可以给你针对性的优化方案 + 示例代码。