0Pricing
Python Academy · Lesson

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

  1. CPython Reference Counting
  2. The Garbage Collector and Cyclic References
  3. Profiling with cProfile and line_profiler
  4. Memory Profiling with tracemalloc
← Back to Python Academy