Profiling with cProfile and line_profiler
Find CPU hotspots with cProfile and line-by-line profiling.
Why Profile?
Profiling identifies which functions consume the most time, guiding optimisation efforts. Always profile before optimising — never guess.
import cProfile
def slow():
total = 0
for i in range(1_000_000):
total += i
return total
cProfile.run("slow()")Running cProfile from CLI
Profile an entire script without modifying it: python -m cProfile -s cumtime script.py. Sort by cumtime, tottime, or calls.
# python -m cProfile -s cumtime my_script.py
#
# ncalls tottime percall cumtime percall filename:lineno(function)
# 1000 0.500 0.001 2.100 0.002 utils.py:10(process)All lessons in this course
- CPython Reference Counting
- The Garbage Collector and Cyclic References
- Profiling with cProfile and line_profiler
- Memory Profiling with tracemalloc