Skip to content
IT Vizag
← Async & Performance

Measuring with timeit and cProfile

Lesson 2 of 10 · 2 min read

Measure first, then optimise.

🎬 Video version coming soon — read it now

Optimising without measuring is guessing. Python gives you two tools: timeit for comparing small snippets, and cProfile for finding which part of a whole program is slow.

Quick timing

import time

start = time.perf_counter()
result = sum(x * x for x in range(5_000_000))
print(f"{time.perf_counter() - start:.3f}s")

perf_counter is the most accurate clock for measuring durations.

timeit: fair comparisons

Small snippets vary from run to run. timeit runs them many times:

import timeit

setup = "data = list(range(10_000))"
print(timeit.timeit("[x * 2 for x in data]", setup=setup, number=1000))
print(timeit.timeit("list(map(lambda x: x * 2, data))", setup=setup, number=1000))

In Colab or Jupyter it's even easier:

%timeit [x * 2 for x in range(10_000)]

cProfile: where does the time go?

import cProfile
import pstats

def load():
    return [str(i) for i in range(300_000)]

def clean(rows):
    return [r.strip() for r in rows]

def slow_lookup(rows):
    seen = []
    for r in rows[:5000]:
        if r not in seen:          # list search: slow
            seen.append(r)
    return seen

def main():
    rows = clean(load())
    slow_lookup(rows)

cProfile.run("main()", "profile.out")
pstats.Stats("profile.out").sort_stats("cumulative").print_stats(8)

The output lists each function with:

  • ncalls: how many times it was called
  • tottime: time spent inside the function itself
  • cumtime: time including everything it called

Sort by cumulative to see which big step is slow, then by tottime to find the exact hot spot. Here slow_lookup stands out, and the next lesson fixes it.

From a terminal: python -m cProfile -s cumtime my_script.py.

Visual profilers

  • snakeviz draws cProfile output as an interactive chart
  • py-spy profiles a running program without changing its code
  • line_profiler shows time per line inside one function

A measuring routine

  1. Time the whole job, so you have a baseline.
  2. Profile it to find the slowest function.
  3. Fix only that one.
  4. Re-measure. Keep the change only if it's really faster and still correct.
  5. Repeat until it's fast enough, then stop.
Tip: Always measure with realistic data sizes. Code that's instant with 100 rows can crawl with 100,000.

In one line

Use perf_counter for quick timing, timeit to compare snippets fairly, and cProfile to find which function is actually slow.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend