0
0
PythonHow-ToBeginner · 3 min read

How to Use cProfile in Python for Performance Profiling

Use the cProfile module in Python by importing it and running cProfile.run('your_function()') to profile your code's performance. It shows how much time each part of your program takes, helping you find slow spots.
📐

Syntax

The basic syntax to profile a Python function using cProfile is:

  • import cProfile: Import the profiling module.
  • cProfile.run('statement'): Run the statement (usually a function call) to profile.

You can also create a Profile object for more control.

python
import cProfile

cProfile.run('my_function()')
💻

Example

This example shows how to profile a simple function that calculates the sum of squares from 0 to 9999. It demonstrates how cProfile reports the time spent in each function call.

python
import cProfile

def sum_squares():
    total = 0
    for i in range(10000):
        total += i * i
    return total

cProfile.run('sum_squares()')
Output
4 function calls in 0.001 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.001 0.001 0.001 0.001 <string>:1(<module>) 1 0.000 0.000 0.001 0.001 example.py:3(sum_squares) 1 0.000 0.000 0.000 0.000 {built-in method builtins.exec} 10000 0.000 0.000 0.000 0.000 {built-in method builtins.range}
⚠️

Common Pitfalls

Common mistakes when using cProfile include:

  • Profiling code that runs too fast to measure meaningfully.
  • Not wrapping the code to profile in a function, which can clutter output.
  • Using cProfile.run() with complex statements without quotes.

Always profile functions or simple statements as strings.

python
import cProfile

# Wrong: passing function directly without quotes
# cProfile.run(sum_squares())  # This runs the function immediately, not profiling

# Right: pass the function call as a string
cProfile.run('sum_squares()')
📊

Quick Reference

CommandDescription
import cProfileImport the profiling module
cProfile.run('func()')Profile the function call 'func()'
cProfile.runctx(stmt, globals, locals)Profile statement with context
p = cProfile.Profile()Create a Profile object for manual control
p.enable() / p.disable()Start and stop profiling manually
p.print_stats()Print collected profiling stats

Key Takeaways

Use cProfile.run() with a string containing the function call to profile code.
Wrap code to profile inside functions for clearer and more useful output.
Avoid calling functions directly inside cProfile.run() without quotes.
Use Profile objects for advanced profiling control and manual start/stop.
Review the output to identify slow parts of your code for optimization.