0
0
PythonHow-ToBeginner · 3 min read

How to Profile Python Code: Simple Steps with cProfile

To profile Python code, use the built-in cProfile module which measures the time spent in each function. Run your script with python -m cProfile your_script.py or use cProfile.run() inside your code to get detailed performance stats.
📐

Syntax

The cProfile module provides tools to measure how much time your program spends in each function. You can use it in two main ways:

  • Run your script from the command line with python -m cProfile your_script.py.
  • Use cProfile.run('your_function()') inside your Python code to profile specific parts.

This helps you see which functions take the most time and where to optimize.

python
import cProfile

# Profile a function call
cProfile.run('sum(range(1000000))')
Output
4 function calls in 0.059 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.058 0.058 0.058 0.058 <string>:1(<module>) 1 0.000 0.000 0.058 0.058 {built-in method builtins.sum} 1 0.000 0.000 0.000 0.000 {built-in method builtins.range} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
💻

Example

This example shows how to profile a function that calculates the sum of squares from 0 to 99999. It uses cProfile.run() to print the time spent in each function call.

python
import cProfile

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

cProfile.run('sum_squares(100000)')
Output
100003 function calls in 0.027 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 100000 0.020 0.000 0.020 0.000 <string>:1(sum_squares) 1 0.007 0.007 0.027 0.027 <string>:1(<module>) 1 0.000 0.000 0.027 0.027 {built-in method builtins.exec} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
⚠️

Common Pitfalls

1. Profiling too much code at once: Profiling your entire program can produce overwhelming data. Focus on specific functions or code blocks.

2. Ignoring output interpretation: The output shows ncalls (number of calls), tottime (time spent in the function itself), and cumtime (time including subcalls). Focus on functions with high tottime or cumtime.

3. Not disabling the profiler: When using cProfile.Profile() objects, remember to call disable() to stop profiling.

python
import cProfile

# Wrong: profiling entire script without focus
cProfile.run('''
for i in range(100000):
    pass
''')

# Right: profile only the function you want

def work():
    for i in range(100000):
        pass

cProfile.run('work()')
📊

Quick Reference

Here is a quick summary of commands and tips for profiling Python code:

Command / ConceptDescription
python -m cProfile your_script.pyProfile entire script from command line
cProfile.run('function()')Profile a specific function call inside code
ncallsNumber of times a function was called
tottimeTime spent in the function itself (excluding calls)
cumtimeTotal time spent in function including subcalls
disable()Stop the profiler when using Profile objects

Key Takeaways

Use the built-in cProfile module to measure where your Python code spends time.
Run profiling from the command line or inside your code with cProfile.run().
Focus on functions with high total or cumulative time to optimize performance.
Avoid profiling too much code at once to keep output manageable.
Interpret profiling results by looking at number of calls, total time, and cumulative time.