How to profile a Python program using cProfile

cProfile is one of the many profilers that ship with Python.

To profile a function in your Python program:

# Assuming we want to profile function doMain()
import cProfile
cProfile.run( "doMain( a, b )" )

When a function call is executed with the profiler, it prints out detailed profiling information after the function call finishes execution.

To dump the profiler statistics to a file named foo.stats:

# Assuming we want to profile function doMain()
import cProfile
cProfile.run( "doMain( a, b )", filename="foo.stats" )

The stats file is not human readable, but is written in the pstats format. This can be opened by using the pstats Python module in a script or using other tools that understand this format.

To profile a Python program named foo.py:

$ python -m cProfile foo.py

To profile a Python program and dump the profiler statistics to a file named foo.stats:

$ python -m cProfile -o foo.stats foo.py

Tried with: Python 2.7.6 and Ubuntu 14.04

Advertisements

2 thoughts on “How to profile a Python program using cProfile”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s