首页 > 解决方案 > 如何识别我的 python 脚本运行缓慢的位置

问题描述

我正在返回一个功能性 Python 脚本,目的是优化运行时。在大多数情况下,我一直在使用 timeit 和 tq​​md 来跟踪单个函数的运行时间,但是有没有办法运行单个函数并跟踪 python 脚本中所有命令的性能以获得单个输出?

例如:

def funct_a(a):
    print(a)
def funct_b(b):
    complex_function(a)
def funct_c(c):
    return c -5

funct_a(5)
funct_b(Oregon)
funct_c(873)

理想情况下,我希望看到一些性能检查的输出,如下所示:

funct_a runtime:.000000001 ms
funct_b runtime: 59 ms
funct_c runtime: .00000002 ms

任何想法将不胜感激

标签: pythonoptimizationruntime

解决方案


使用分析器。

我喜欢使用名为 cProfile 的默认分析器(已包含在 python 中)。

然后,您可以使用snakeviz 可视化数据。

这是如何使用它的粗略方法:

import cProfile
import pstats

with cProfile.Profile() as pr:
    {CODE OR FUNCTION HERE}

stats = pstats.Stats(pr)
stats.sort_stats(pstats.SortKey.TIME)
# Now you have two options, either print the data or save it as a file
stats.print_stats() # Print The Stats
stats.dump_stats("File/path.prof") # Saves the data in a file, can me used to see the data visually

现在将其可视化:

  1. 安装snakeviz
  2. 转到您的文件路径
  3. 打开 cmd/终端并输入snakeviz filename.prof

如需进一步说明,请观看此视频: https ://www.youtube.com/watch?v=m_a0fN48Alw&t=188s&ab_channel=mCoding


推荐阅读