【问题标题】:Check running time per line in python检查python中每行的运行时间
【发布时间】:2013-06-23 06:07:54
【问题描述】:

我编写了一个 Python 脚本,但运行它所花费的时间比我预期的要长得多,而且我没有明显的候选者在脚本中占用运行时的特定行。

我可以在我的代码中添加什么来检查每行运行需要多长时间?

非常感谢。

【问题讨论】:

标签: python performance profiling


【解决方案1】:

您是否尝试过使用 profiling 运行 python?

python -m cProfile --sort cumulative your_single_thread_script.py &> out.log

您可以在这个问题How can you profile a python script?中找到更多详细信息

您可以阅读有关分析实用程序here 的更多信息。

【讨论】:

  • 如果我有一个脚本调用一堆其他脚本,我如何检查每个脚本的时间?
【解决方案2】:

使用分析器,例如hotshot。很简单!

1) 使用配置文件运行您的代码:

import hotshot

prof = hotshot.Profile("hotshot_stats.prof")
prof.runcall(my_function)
prof.close()

2) 读取结果文件:

from hotshot import stats

s = stats.load("hotshot_stats.prof")
s.strip_dirs()
s.sort_stats('time', 'calls')
s.print_stats(20)

【讨论】:

    【解决方案3】:

    timeit 是自 python 2.3 以来的标准模块,请查看它的文档。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-07
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多