Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you profile a Python script?

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?

like image 284
Chris Lawlor Avatar asked Feb 24 '09 16:02

Chris Lawlor


People also ask

What is profile file in python?

Introduction to the profilers cProfile and profile provide deterministic profiling of Python programs. A profile is a set of statistics that describes how often and for how long various parts of the program executed. These statistics can be formatted into reports via the pstats module.

How do you use line profiler in python?

1) Installed line_profiler from pypi by using the .exe file (I am on WinXP and Win7). Just clicked through the installation wizard. 2) Written a small piece of code (similar to what has been asked in another answered question here). 3) Run the code from IDLE/PyScripter.

How do you run a memory profiling in python?

The easiest way to profile a single method or function is the open source memory-profiler package. It's similar to line_profiler , which I've written about before . You can use it by putting the @profile decorator around any function or method and running python -m memory_profiler myscript.


1 Answers

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()') 

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

python -m cProfile myscript.py 

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 

And 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 <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} 

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

like image 120
Chris Lawlor Avatar answered Sep 22 '22 11:09

Chris Lawlor