How to use cProfile to profile Python code

Why is your Python app so slow? Find out by using Python’s built-in profiler to locate bottlenecks in your Python code

Become An Insider

Sign up now and get FREE access to hundreds of Insider articles, guides, reviews, interviews, blogs, and other premium content. Learn more.

Python may not be the fastest language around, but it is often fast enough. And Python is ideal when programmer time matters more than CPU time.

That said, if a given Python app is laggy, you’re not obliged to just suck it up. Tools included with the stock installation of the Python interpreter can provide you with detailed feedback about which parts of your program are slow, and offer some hints about how to speed them up.

How to use cProfile

The cProfile module gathers statistics about the execution time of a Python program. It can report on anything from the entire app to a single statement or expression.

Here is a toy example of how to use cProfile:

To continue reading this article register now