How do I profile Python code

Profiling Python code is essential for optimizing performance and identifying bottlenecks in your application. Python provides several built-in modules and external libraries that can help you profile your code effectively. Here’s a simple guide on how to get started with profiling your Python code.

Using cProfile

The most common way to profile Python code is by using the cProfile module, which provides a comprehensive way to analyze the performance of your functions.

Here’s an example of how to use cProfile:

import cProfile def my_function(): total = 0 for i in range(10000): total += i return total cProfile.run('my_function()')

In this example, we define a simple function my_function that computes the sum of numbers from 0 to 9999. The cProfile.run method then executes the function and provides a detailed report on the time spent in each function call.

Using Line Profiler

For more granular profiling, you can use the line_profiler package. This tool allows you to see how much time is spent on each individual line of a function.

To use it, you would first need to install the package:

pip install line_profiler

After installation, you can use it to profile specific functions by using the @profile decorator.


Profiling Python cProfile line_profiler optimize Python code Python performance