195. Python Profiling

Profiling is a way to identify performance bottlenecks in your Python code. By using cProfile or profile, you can measure the time taken by various parts of your code and identify which functions are consuming the most resources. Here are 10 Python code snippets demonstrating how to use profiling with cProfile and profile.


1. Basic Profiling with cProfile

import cProfile

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

# Profiling the function
cProfile.run('slow_function()')

2. Profiling a Function in a Larger Script

import cProfile

def function_a():
    sum(range(10000))

def function_b():
    for i in range(100):
        sum(range(10000))

def main():
    function_a()
    function_b()

# Profiling the entire main function
cProfile.run('main()')

3. Saving Profiling Results to a File


4. Using pstats to Analyze Profiling Data


5. Profiling with Different Sorting Options


6. Profiling Multiple Functions


7. Viewing Profiling Data in Graphical Format (using snakeviz)

After running a script with cProfile, you can visualize the results:


8. Profiling a Class Method


9. Using profile for More Granular Control (Profiling a Specific Code Block)


10. Profiling with a Decorator for Easy Reuse


Key Concepts:

  1. Profiling: cProfile and profile allow you to monitor function call statistics, including execution time.

  2. Sorting Stats: You can sort the results based on time, number of calls, or other metrics to identify performance bottlenecks.

  3. Saving Output: You can save profiling results to a file and analyze it later, even in graphical formats like snakeviz.

  4. Profile Specific Functions: By using decorators or manual profiling commands, you can profile individual parts of your code or entire scripts.

  5. Granular Profiling with profile: Provides more detailed control over profiling specific code blocks.

Profiling helps you pinpoint areas in your code that need optimization, making it an essential tool for performance tuning.

Last updated