如何确定我的 python 脚本在哪里运行缓慢 运行

How to identify where my python script is slow running

我正在返回功能性 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

任何想法将不胜感激

import time

start = time.time()
#code goes here
end = time.time()
print('Time for code to run: ', end - start)

使用分析器。

我喜欢使用名为 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/terminal 并输入 snakeviz filename.prof

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

使用timeit模块:

import timeit

def funct_a(a):
    return a

def funct_b(b):
    return [b]*20
    
def funct_c(c):
    return c-5

>>> print(timeit.timeit('funct_a(5)', globals=globals()))
0.09223939990624785

>>> print(timeit.timeit('funct_b("Oregon")', globals=globals()))
0.260303599992767

>>> print(timeit.timeit('funct_c(873)', globals=globals()))
0.14657660003285855