如何分析 Python 脚本? [英] How can you profile a Python script?

查看:49
本文介绍了如何分析 Python 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Project Euler 和其他编码竞赛通常有最长的运行时间或人们吹嘘如何快速运行他们的特定解决方案.使用 Python,有时这些方法有点笨拙 - 即,将计时代码添加到 __main__.

Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With Python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to __main__.

分析 Python 程序运行时间的好方法是什么?

What is a good way to profile how long a Python program takes to run?

推荐答案

Python 包含一个名为 cProfile.它不仅给出了总运行时间,还给出了每个函数的单独计时,并告诉你每个函数被调用了多少次,从而很容易确定你应该在哪里进行优化.

Python includes a profiler called cProfile. It not only gives the total running time, but also times each function separately, and tells you how many times each function was called, making it easy to determine where you should make optimizations.

您可以在代码中或从解释器中调用它,如下所示:

You can call it from within your code, or from the interpreter, like this:

import cProfile
cProfile.run('foo()')

更有用的是,您可以在运行脚本时调用 cProfile:

Even more usefully, you can invoke the cProfile when running a script:

python -m cProfile myscript.py

为了更简单,我制作了一个名为profile.bat"的小批处理文件:

To make it even easier, I made a little batch file called 'profile.bat':

python -m cProfile %1

所以我所要做的就是运行:

So all I have to do is run:

profile euler048.py

我明白了:

1007 function calls in 0.061 CPU seconds

Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    1    0.000    0.000    0.061    0.061 <string>:1(<module>)
 1000    0.051    0.000    0.051    0.000 euler048.py:2(<lambda>)
    1    0.005    0.005    0.061    0.061 euler048.py:2(<module>)
    1    0.000    0.000    0.061    0.061 {execfile}
    1    0.002    0.002    0.053    0.053 {map}
    1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler objects}
    1    0.000    0.000    0.000    0.000 {range}
    1    0.003    0.003    0.003    0.003 {sum}

更新了来自 PyCon 2013 的优质视频资源的链接,标题为Python 分析
也通过 YouTube.

Updated link to a good video resource from PyCon 2013 titled Python Profiling
Also via YouTube.

这篇关于如何分析 Python 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆