# cProfile-性能分析
# 概述
cProfile是Python标准库中的一个性能分析工具,可以用于分析Python程序的运行性能,帮助开发者找出程序的瓶颈,并进行优化。
cProfile模块提供了一种比较低级的性能分析方式,可以对程序中的每个函数进行分析,记录函数的调用次数、执行时间等信息,并输出性能分析结果。与其它性能分析工具相比,cProfile具有低开销、准确性高等优点,因此被广泛使用。
以下是cProfile模块中常用的函数和类:
- cProfile.run(command[, filename]):运行命令并对其进行性能分析。命令可以是一个函数或语句,filename参数用于指定性能分析结果保存到文件的路径。
- cProfile.Profile():创建一个Profile对象,用于对Python程序进行性能分析。
- Profile.enable()和Profile.disable():开启或关闭性能分析。
- Profile.run(command[, filename]):运行命令并对其进行性能分析,功能和cProfile.run()相同,但是可以使用Profile对象进行更加灵活的配置和控制。
- Profile.dump_stats(filename):将性能分析结果保存到文件。
- Profile.print_stats([sort_order, num]):输出性能分析结果。sort_order参数用于指定排序方式,num参数用于指定输出的函数数量。
- pstats.Stats(profile):创建一个Stats对象,用于对Profile对象的性能分析结果进行统计和展示。
- Stats.strip_dirs():去除文件路径,只显示函数名。
- Stats.sort_stats([key, sort_order]):对性能分析结果进行排序。key参数用于指定排序方式,sort_order参数用于指定排序顺序。
- Stats.print_stats([num, strip_dirs, percent]):输出性能分析结果,num参数用于指定输出的函数数量,strip_dirs参数用于去除文件路径,percent参数用于显示每个函数的执行时间占总时间的百分比。
- Stats.print_callers([num, strip_dirs]):输出调用指定函数的函数列表,num参数用于指定输出的函数数量,strip_dirs参数用于去除文件路径。
- Stats.print_callees([num, strip_dirs]):输出被指定函数调用的函数列表,num参数用于指定输出的函数数量,strip_dirs参数用于去除文件路径。
# 使用示例
以下是一个简单的cProfile使用示例,在这个示例中,我们定义了两个函数func1和func2,分别模拟了一些计算密集型的操作。然后,在主函数main中,我们多次调用这两个函数,模拟了一些计算密集型的场景。最后,我们使用cProfile.run()函数对主函数进行性能分析。
这个结果包含了每个函数的调用次数、执行时间、累计时间等信息。可以看到,func1和func2函数的调用次数和执行时间都被正确地记录下来了,因此我们可以根据这些信息找出程序的瓶颈,并进行优化。
import cProfile
import time
def func1():
time.sleep(1)
def func2():
time.sleep(2)
def main():
for i in range(5):
func1()
for i in range(3):
func2()
if __name__ == '__main__':
cProfile.run('main()')
"""
20 function calls in 11.080 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 11.079 11.079 <string>:1(<module>)
1 0.000 0.000 11.079 11.079 cprofile_test.py:10(main)
5 0.000 0.000 5.049 1.010 cprofile_test.py:4(func1)
3 0.000 0.000 6.031 2.010 cprofile_test.py:7(func2)
1 0.000 0.000 11.080 11.080 {built-in method builtins.exec}
8 11.079 1.385 11.079 1.385 {built-in method time.sleep}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
"""