snippetpythonCritical
How do I profile a Python script?
Viewed 0 times
profilehowscriptpython
Problem
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
What is a good way to profile how long a Python program takes to run?
__main__.What is a good way to profile how long a Python program takes to run?
Solution
Python includes a profiler called
You can call it from within your code, or from the interpreter, like this:
Even more usefully, you can invoke cProfile when running a script:
Or when running a module:
To make it even easier, I made a little batch file called 'profile.bat':
So all I have to do is run:
And I get this:
For more information, check out this tutorial from PyCon 2013 titled
Python Profiling
Also via YouTube.
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()')Even more usefully, you can invoke cProfile when running a script:
python -m cProfile myscript.pyOr when running a module:
python -m cProfile -m mymoduleTo make it even easier, I made a little batch file called 'profile.bat':
python -m cProfile %1So all I have to do is run:
profile euler048.pyAnd I get this:
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 :1()
1000 0.051 0.000 0.051 0.000 euler048.py:2()
1 0.005 0.005 0.061 0.061 euler048.py:2()
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}
For more information, check out this tutorial from PyCon 2013 titled
Python Profiling
Also via YouTube.
Code Snippets
import cProfile
cProfile.run('foo()')python -m cProfile myscript.pypython -m cProfile -m mymodulepython -m cProfile %1profile euler048.pyContext
Stack Overflow Q#582336, score: 1823
Revisions (0)
No revisions yet.