How to Profile Python Code: Simple Steps with cProfile
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.
import cProfile # Profile a function call cProfile.run('sum(range(1000000))')
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.
import cProfile def sum_squares(n): total = 0 for i in range(n): total += i * i return total cProfile.run('sum_squares(100000)')
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.
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 / Concept | Description |
|---|---|
| python -m cProfile your_script.py | Profile entire script from command line |
| cProfile.run('function()') | Profile a specific function call inside code |
| ncalls | Number of times a function was called |
| tottime | Time spent in the function itself (excluding calls) |
| cumtime | Total time spent in function including subcalls |
| disable() | Stop the profiler when using Profile objects |