在Debian上进行Python性能测试,可按以下步骤操作,根据需求选择合适工具:
sudo apt update
sudo apt install python3 python3-pip # 确保Python和pip已安装
pip3 install pytest locust memory_profiler line_profiler py-spy # 安装常用测试工具
# test_example.py
import pytest
def test_performance():
assert sum(range(100000)) == 4999950000 # 示例断言
运行命令:pytest --benchmark-autosave=results.json test_example.py # 保存基准结果
cProfile(标准库):分析函数执行时间与调用次数。
python3 -m cProfile -o profile_data.py example.py # 生成性能数据文件
python3 -m pstats profile_data.py # 查看分析结果
line_profiler:逐行分析代码性能,需在函数前加@profile
装饰器。
kernprof -l -v example.py # 输出每行代码的执行时间与调用次数
memory_profiler:监控内存使用情况,支持逐行分析。
mprof run example.py # 记录内存使用
mprof plot # 生成内存使用图表
locustfile.py
:from locust import HttpUser, task
class MyUser(HttpUser):
@task
def test_endpoint(self):
self.client.get("/api/test")
locust -f locustfile.py --host=http://localhost:8000
http://localhost:8089
设置并发用户数,查看实时性能数据。py-spy:实时分析运行中的Python进程,生成火焰图或性能数据。
py-spy top --pid <进程ID> # 实时查看CPU/内存使用
py-spy record -o profile.svg --pid <进程ID> # 生成调用栈火焰图
NetData:系统级监控工具,可监控CPU、内存、网络等指标。
sudo apt install netdata
systemctl start netdata
访问 http://服务器IP:19999 查看实时数据
参考来源: