Profiling Python Code with cProfile

Finding bottlenecks in your code can help you write more performant scripts and procedures. Python’s standard library includes a profiling module named cProfile to help you find where your program is spending its time; you’ll learn about cProfile in this section.

In general, to use cProfile you can do the following:

  1. Enable a profiler and run the code you’d like to profile (disabling the profiler when you are done).

  2. Investigate the Stats produced by the profiling session.[67]

Let’s try this out with an example. cprofile_example.py profiles the function named a and writes the Stats to a file named example.stats:

1: import​ ​cProfile
def​ ​a​():
b()
5:  b()
def​ ​b​():
​ ...

Get Intuitive Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.