python - 如何识别我的 python 脚本运行缓慢的位置
问题描述
我正在返回一个功能性 Python 脚本,目的是优化运行时。在大多数情况下,我一直在使用 timeit 和 tqmd 来跟踪单个函数的运行时间,但是有没有办法运行单个函数并跟踪 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
任何想法将不胜感激
解决方案
使用分析器。
我喜欢使用名为 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
现在将其可视化:
- 安装snakeviz
- 转到您的文件路径
- 打开 cmd/终端并输入
snakeviz filename.prof
如需进一步说明,请观看此视频: https ://www.youtube.com/watch?v=m_a0fN48Alw&t=188s&ab_channel=mCoding
推荐阅读
- mysql - 如果mysql表不存在则创建,否则添加缺少的列?
- reactjs - 在 React 中自动配置 Firebase SDK
- python - 在 python 中使用 opencv 在图像中显示特定颜色周围的边界
- java - NoClassDefFoundError:解析失败:DataBinderMapper
- c - C中的二进制文件
- asterisk - Asterisk 中不同的详细级别有什么作用?
- c# - 如何在工作完成时禁用网格?
- hive - Hive 和 Google Cloud Storage 的问题
- css - 如何在 CSS 中选择此元素?
- flutter - ListView 在列表顶部时与元素重叠