Ubuntu下Python性能测试的常用方法与工具
在Ubuntu系统中,Python性能测试可分为代码级基准测试(测量小段代码执行时间)、程序级性能分析(识别函数/行级瓶颈)、负载测试(模拟高并发场景)三类,以下是具体工具与操作指南:
timeit模块(Python标准库)time.time()的系统调用开销)。import timeit
# 测试sum(range(1000))的执行时间(重复1000次取平均)
elapsed = timeit.timeit('sum(range(1000))', number=1000)
print(f"平均执行时间: {elapsed:.6f}秒")
time模块(Python标准库)perf_counter()获取高精度时间戳,适合测量较长时间代码块的执行时间。import time
start = time.perf_counter() # 高精度计时开始
# 待测试代码(如排序10万个元素)
result = sorted([i**2 for i in range(100000)])
end = time.perf_counter() # 高精度计时结束
print(f"执行时间: {end - start:.4f}秒")
perf_counter()比time.time()更适合性能测试,因为它不受系统时间调整的影响。cProfile模块(Python标准库)import cProfile
def fibonacci(n):
return n if n < 2 else fibonacci(n-1) + fibonacci(n-2)
# 生成分析报告(保存到profile.txt)
cProfile.run('fibonacci(30)', 'profile.txt')
snakeviz工具可视化报告(pip install snakeviz; snakeviz profile.txt),快速定位耗时最深的函数(如递归中的重复计算)。line_profiler模块(第三方库)cProfile更细致。pip install line_profiler
from line_profiler import profile
@profile # 添加装饰器标记需分析的函数
def fibonacci(n):
return n if n < 2 else fibonacci(n-1) + fibonacci(n-2)
fibonacci(30) # 运行后会生成逐行分析报告
memory_profiler模块(第三方库)pip install memory_profiler
from memory_profiler import profile
@profile
def create_large_list():
return [i**2 for i in range(1000000)] # 生成100万个元素的列表
create_large_list()
mprof plot命令生成内存使用趋势图,识别内存泄漏(如未释放的大对象)。py-spy工具(第三方库)pip install py-spy
py-spy top --pid <Python进程ID> # 替换为实际PID(通过ps aux | grep python获取)
py-spy record -o profile.svg --pid <Python进程ID>
Locust框架(第三方库)pip install locust
locustfile.py):from locust import HttpUser, task, between
class WebsiteUser(HttpUser):
# 用户等待时间(1~5秒)
wait_time = between(1, 5)
# 定义任务(权重为1)
@task(1)
def homepage(self):
self.client.get("/") # 访问首页
# 定义任务(权重为2,执行频率更高)
@task(2)
def about_page(self):
self.client.get("/about") # 访问关于页
locust -f locustfile.py --host=http://example.com # 替换为目标URL
http://localhost:8089,设置并发用户数(如1000)、生成速率(如100用户/秒),实时监控响应时间、失败率、吞吐量(Requests/s)。top/htop命令top # 按“P”键按CPU排序,按“M”键按内存排序
htop # 更直观的界面(需安装:sudo apt install htop)
vmstat命令vmstat 1 5 # 每1秒刷新一次,共5次
输出字段说明:r(运行队列长度,反映CPU负载)、us(用户态CPU使用率)、sy(内核态CPU使用率)、free(空闲内存)。timeit或time.perf_counter()。cProfile(整体函数分析)+line_profiler(逐行分析)+memory_profiler(内存分析)。py-spy(无侵入性)。Locust(分布式、易扩展)。top/htop/vmstat(辅助判断系统瓶颈)。