使用pstats模块对Python程序进行性能分析与比较
发布时间:2023-12-15 19:01:29
pstats模块是Python内置的性能分析工具,可以用来分析Python程序中的函数调用信息、时间消耗以及函数的调用次数等。下面是一个使用pstats模块的例子:
首先,我们需要在代码中导入cProfile模块,并使用cProfile.run()方法来运行我们要分析的代码。例如,我们要分析一个名为my_func()的函数:
import cProfile
def my_func():
for i in range(100000):
pass
cProfile.run('my_func()')
运行上述代码后,会得到类似如下的输出:
3 function calls in 0.003 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.003 0.003 0.003 0.003 <ipython-input-1-0263e3a96f79>:3(my_func)
1 0.000 0.000 0.003 0.003 <string>:1(<module>)
1 0.000 0.000 0.003 0.003 {built-in method builtins.exec}
上面的输出中包含了函数调用的次数、总时间、每次调用的时间以及每个函数的详细信息。
接下来,我们可以利用pstats模块加载这些分析结果,并对其进行更详细的分析。下面是一个例子:
import pstats
p = pstats.Stats('output')
p.sort_stats('cumulative').print_stats(10)
上面的代码中,我们使用Stats类加载保存在文件output中的分析结果,并使用sort_stats()方法对这些结果进行排序。使用print_stats()方法可以打印出前10个累计时间最长的函数。
p.sort_stats('cumulative')表示按照函数调用的累计时间进行排序。其他可用的排序方式包括'ncalls'(函数调用次数)、'tottime'(函数总时间)和'percall'(平均每次调用的时间)。
另外,我们还可以使用strip_dirs()方法去除路径信息,并使用add()方法添加其他的分析结果文件。下面是一个完整的例子:
import pstats
p = pstats.Stats('output')
p.strip_dirs().sort_stats('tottime').print_stats(10)
p.add('output2')
p.strip_dirs().sort_stats('tottime').print_stats(10)
上面的例子中,我们先加载了一个分析结果文件output,并使用strip_dirs()方法去除路径信息,然后按照函数总时间进行排序并打印前10个结果。接着,我们使用add()方法添加了另一个分析结果文件output2,并再次进行排序和打印。
通过pstats模块,我们可以对Python程序进行深入的性能分析,并比较不同结果文件之间的差异,从而找到程序的性能瓶颈,进行优化。
