性能测试
编写程序完毕后,一般需要考虑下其时间复杂度和空间复杂度。随着内存的增大以及服务器计算能力的提升,大多数情况是不会遇到时间不满足要求,空间不满足要求的问题,而对于某些特殊场景下就需要考虑程序运行耗费时间,比如服务接口时候需要考虑请求响应速度,对于移动设备而言,要考虑内存空间大小。在python中,也提供了一些性能测试的标准库。
timeit
timeit,用于测量少量代码片段的执行时间。基本算法思路是执行较多的次数,从中选取最小平均值。
- 将代码循环执行多次(number, -n),以便有足够长的统计时间;
- 将上述步骤循环执行多次(repeat, -r), 获取足够多的统计采样;
- 从上述步骤的结果中选取耗时最短的采样,计算单词平均值。
python -m timeit -n 10 -r 3 -s "import time" "time.sleep"
10 loops, best of 3: 1 sec per loop
上述命令集合了两个过程:
- timeit.timeit
- timeit.repeat
profile
profile模块用于测量执行过程中函数的执行时间和调用次数
def sum(m):
n = 0
for i in range(m):
n += i
return n
def main():
for i in range(3):
sum(1000000)
n = 0
for i in range(1000000):
n += i
if __name__ == "__main__":
main()
终端执行
python -m cProfile -s cumtime test.py
其中参数意思:
- ncalls: 被调用的次数
- tottime: 总执行时间
- precall:tottime / ncalls
- cumtime: 执行总耗时, 包括调用子函数
- percall:cumtime / ncalls
line_profiler
line_profiler 可以对函数内的代码逐行进行测试
首先安装:pip install line_profiler
def test(n):
a = []
for i in range(n):
a.extend([1] * (10 ** 6))
return a
def run():
a = test(2)
return a
- Line: 函数内源码的行号
- Hits:执行次数
- Time:总计执行次数
- Per Hit: 单词执行的平均时间
- % Time: 占总耗时的百分比
- Line Contents: 源代码
memory_profiler
memory_profiler 用于逐行分析代码内存占用。
首先安装:pip install memory_profiler
@profile
def test():
a = [1] * (10 ** 6)
b = [2] * (2 * 10 ** 7)
del b
return a
if __name__ == "__main__":
test()
python -m memory_profiler memory_test.py
- Mem usage: 执行程序后,解释器内存使用总量
- Increment: 相对于上一行的内存使用增量;