Skip to Content
Intuitive Python
book

Intuitive Python

by David Muller
May 2021
Intermediate to advanced
142 pages
3h 37m
English
Pragmatic Bookshelf
Content preview from Intuitive Python

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​():
​ ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Pythonic Programming

Pythonic Programming

Dmitry Zinoviev
Python for Geeks

Python for Geeks

Muhammad Asif

Publisher Resources

ISBN: 9781680508635Errata Page