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__.
What is a good way to profile how long a Python program takes to run?
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:
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:
EDIT: Updated link to a good video resource from PyCon 2013 titled Python Profiling
Also via YouTube.