86. Performance Profiling with cProfile

Performance profiling in Python can help identify slow sections of code and improve overall performance. The cProfile module is a built-in tool for profiling Python programs, providing valuable insight into the execution time of different functions or methods.

Here are 10 Python code snippets demonstrating how to use cProfile to profile code and identify performance bottlenecks:

1. Basic Profiling with cProfile

import cProfile

def slow_function():
    total = 0
    for i in range(1000000):
        total += i
    return total

# Profile the slow function
cProfile.run('slow_function()')

This is the simplest usage of cProfile. It runs the function slow_function and outputs a profile of how long each part of the code took to execute.


2. Profiling Multiple Functions

import cProfile

def function_a():
    total = 0
    for i in range(500000):
        total += i
    return total

def function_b():
    total = 0
    for i in range(1000000):
        total += i
    return total

# Profile both functions
cProfile.run('function_a()')
cProfile.run('function_b()')

This example profiles two functions separately to observe their individual performance.


3. Profiling Code in a Script

You can use cProfile.run() to profile the main execution of a script.


4. Saving Profile Data to a File

This code saves the profiling data to a file named profile_data.prof for further inspection.


5. Viewing Profiling Results with pstats

This snippet loads the profiling data from a file and sorts the output by cumulative time. The print_stats(10) method prints the top 10 functions by cumulative time.


6. Profiling with the time Method for Comparison

This code compares cProfile output with a simple manual timing approach using time.time().


7. Profiling Code with a Decorator

This example defines a custom decorator profile_function to profile the execution of any function it wraps.


8. Profiling Using a Context Manager

Here, the context manager profile_context is used to start and stop profiling for a specific block of code.


9. Profiling External Libraries

This example demonstrates profiling a function that includes an external library (in this case, time.sleep).


10. Profiling with runctx for Code with Context

This snippet demonstrates profiling code within a specific namespace using cProfile.runctx().


These examples show how to use cProfile in various scenarios, from simple function profiling to profiling code with decorators and context managers. You can utilize these techniques to identify performance bottlenecks in your Python code and optimize its execution.

Last updated