Skip to content

Lesson 40 of 52Concurrency and performance

Profiling and Making Python Fast

Measure before you optimise: timeit, cProfile, sampling profilers and tracemalloc, then the fixes that matter, shown on a real 35x speed-up.

18 min read0/4 questions

A nightly export script used to take four minutes. Now it takes forty, and the data only doubled. Someone suggests rewriting it in Go. Someone else wants to add a process pool. Both are guesses. In most cases like this one, a profiler finds a single line, often a membership test on a list inside a loop, and a one-word change fixes it. This lesson teaches the measuring tools first, then the fixes in the order they usually pay off, and ends with a worked case that goes from 300 ms to under 9 ms without leaving the standard library.

Measure first, and measure properly

Intuition about speed is wrong surprisingly often, even for experienced engineers. So the rule is: no optimisation without a number before and a number after.

For a whole program or one request, wrap it with time.perf_counter(). It is the clock meant for measuring short intervals: high resolution, and it never jumps backwards when the system clock changes. Do not use time.time() for this.

For a small snippet, use timeit. It runs the statement many times in a loop, turns off garbage collection while it times, and lets you repeat the whole measurement to see the noise:

Python
import timeit setup = "ids = list(range(10_000)); id_set = set(ids)"for label, stmt in [ ("9_999 in list", "9_999 in ids"), ("9_999 in set", "9_999 in id_set"),]: # repeat() runs the whole timing 5 times; keep the best (least noisy) run runs = timeit.repeat(stmt, setup=setup, number=2_000, repeat=5) per_call_us = min(runs) / 2_000 * 1e6 print(f"{label:<15} {per_call_us:8.3f} us per check")
Output
Press Run (⌘ Enter) to see what happens.

Thousands of times faster for the set, because a set is a hash table and a list is a scan. The same tool works from the terminal, where it picks the loop count for you:

python -m timeit -s "ids = list(range(10_000))" "9_999 in ids"

In Jupyter or IPython, %timeit expr does the same.

Why the best of several runs, not the average? Noise on a busy machine only ever makes code slower. The fastest run is the closest to the true cost of the code. Other traps that make benchmarks lie:

  • No warm-up. The first run pays for imports, cache misses and, since 3.11, the interpreter specialising hot bytecode. Discard it.
  • Measuring the wrong thing. Building test data inside the timed statement, or timing a function whose result is then thrown away by an optimising library.
  • Laptop on battery, other programs running, thermal throttling. Compare numbers taken on the same machine in the same session.
  • Tiny inputs. An O(n²) algorithm can beat an O(n log n) one at n = 10 and lose badly at n = 100,000. Benchmark at production sizes.
Predict the outputPython

What does this print?

import timeit

calls = 0

def work():
  global calls
  calls += 1

timeit.repeat(work, number=100, repeat=3)
print(calls)
Need a nudge? Hints walk you through it.

Deterministic profiling with cProfile

timeit tells you how long something takes. A profiler tells you where the time goes. cProfile, in the standard library, is a deterministic (tracing) profiler: it records every function call and return, so its counts are exact. Run a whole script under it from the terminal:

python -m cProfile -s cumulative report.py

or save the data and explore it later:

python -m cProfile -o report.prof report.pypython -m pstats report.prof

The interactive pstats browser accepts commands like sort tottime, stats 15 and callers is_vip. For a picture, snakeviz report.prof (a separate package) opens an icicle chart in your browser. You can also profile just one part of a program from code, which is what the worked case below does.

Each row of the report has these columns:

ColumnMeaning
ncallsHow many times the function was called. 15/1 means 15 calls, 1 of them not recursive.
tottimeTime spent inside this function itself, not counting functions it called.
cumtimeTime from entry to exit, including everything it called.
percalltottime / ncalls, then cumtime / ncalls.

Sort by cumtime to find the slow feature: the top rows are the high-level functions where the time ends up. Sort by tottime to find the slow code: the functions doing the work themselves.

tottime vs cumtime in one call tree
maincumtime 1.00s, tottime 0.01scsv_readertottime 0.20sload_orderscumtime 0.20sis_viptottime 0.60s, called 30,000 timesformat_rowtottime 0.10sbuild_reportcumtime 0.79s, tottime 0.09sroot

main has the biggest cumtime, 1.00 s, because everything runs inside it. Its own tottime is tiny. Sorting by cumtime always puts entry points first.

1/4

Two things a profiler report hides. First, cProfile adds overhead to every function call, so code with many tiny calls looks slower under it than in real life. Use it to find where, then confirm the gain with timeit or perf_counter without the profiler. Second, operations that are not Python function calls, such as x in some_list, + on strings or a slice, have no row of their own. Their cost shows up in the tottime of the function that contains them.

Quick check
In a cProfile report, parse_line has ncalls 1,000,000, tottime 0.4 s, cumtime 6.1 s. What does that tell you?
Need a nudge? A hint rules out a wrong answer.

Sampling profilers for real workloads

A deterministic profiler is great on a laptop. It is wrong for a production server: the overhead is large, and you would have to restart the process to turn it on. A sampling profiler looks at the running program's call stack many times per second and counts what it sees. If is_vip is on top of the stack in 60% of samples, it is using about 60% of the time. Counts are statistical, not exact, but the overhead is low and nothing in your code changes.

The common choice today is py-spy, a separate tool written in Rust:

py-spy top --pid 1234py-spy record -o profile.svg --pid 1234py-spy dump --pid 1234

top is a live view like the Unix top command. record writes a flame graph: the width of each bar is how often that function was on the stack, so the wide bars are where the time goes. dump prints every thread's current stack, which you saw in Threads and the GIL for finding deadlocks. Attaching to another process needs permission: sudo on macOS, and the SYS_PTRACE capability in many container setups.

Python 3.15 adds a sampling profiler to the standard library, profiling.sampling, and moves cProfile's home to profiling.tracing. import cProfile keeps working. The pure-Python profile module is deprecated in 3.15 and scheduled for removal in 3.17. The new sampler can run a script or attach to a process by id:

python -m profiling.sampling run --flamegraph -o profile.html report.pypython -m profiling.sampling attach 1234

These commands come from a pre-release build. Check python -m profiling.sampling --help on your version, because flags in a brand-new module can change.

Match the pairs0/5 matched

Match each question to the tool that answers it.

Choose an item, then its match on the other side.

Measuring memory

Slow code is one problem. Code that is killed by the operating system for using too much memory is another, and it is common in data jobs and containers. Two warnings first. sys.getsizeof(obj) returns the size of one object, not what it refers to: a list's size covers its array of pointers, not the items. And Python rarely gives freed memory back to the OS at once, so the process size from top is a rough signal, not a measurement.

tracemalloc (standard library) records where each allocation happened. Take a snapshot, run the code, take another, and compare:

Python
import sysimport tracemalloc class Point: def __init__(self, x, y): self.x, self.y = x, y class SlotPoint: __slots__ = ("x", "y") def __init__(self, x, y): self.x, self.y = x, y def measure(label, build): tracemalloc.start() before = tracemalloc.take_snapshot() keep = build() # keep it alive while we measure after = tracemalloc.take_snapshot() tracemalloc.stop() total = sum(stat.size_diff for stat in after.compare_to(before, "lineno")) print(f"{label:<28} {total / 1e6:6.2f} MB") return keep measure("100k Point objects", lambda: [Point(i, i) for i in range(100_000)])measure("100k SlotPoint objects", lambda: [SlotPoint(i, i) for i in range(100_000)])measure("list of 100k squares", lambda: [i * i for i in range(100_000)])measure("generator of 100k squares", lambda: (i * i for i in range(100_000))) nested = [[0] * 1000 for _ in range(100)]print("sys.getsizeof(nested):", sys.getsizeof(nested), "bytes <- only the outer list")
Output
Press Run (⌘ Enter) to see what happens.

The browser runs a 32-bit build, so the numbers there are about half of what a 64-bit laptop shows (12.8 MB and 8.8 MB for the two point classes on CPython 3.14). The proportions are what matter. __slots__ removes the per-instance __dict__, which saves about a third here and more on older versions. It matters when you hold millions of small objects. A generator holds one item at a time instead of the whole list, so streaming a file line by line uses constant memory while readlines() loads it all.

In production code, snapshot.statistics("lineno") lists the top allocating lines, which is how you find a leak: take a snapshot, let the service run for an hour, take another, and compare. For bigger jobs, memray (a separate tool from Bloomberg) tracks every allocation, including inside C extensions, and draws a flame graph of memory. It runs on Linux and macOS.

The fixes that matter, in order

Once a profiler has pointed at the hot spot, these are the fixes, roughly in order of how much they usually give back:

  1. A better algorithm or data structure. Membership on a list inside a loop is O(n) per check, so O(n·m) overall. A set or dict makes it O(1). Sorting once and using bisect, or grouping into a dict instead of nested loops, changes the shape of the curve, not just the constant. This is where 10x to 1000x wins come from. Lists covered the costs of each operation, and Big O in the Algorithms & Patterns course explains the curves.
  2. Stop doing repeated work. Move constant work out of the loop (compile the regex once, build the lookup set once). Cache pure functions with functools.cache. Avoid parsing a value fully when you only need part of it. Do not run a database query per row: one query that fetches everything, then a dict lookup, beats a thousand round trips.
  3. Use built-ins and C-backed code. sum, min, sorted, str.join, collections.Counter and comprehensions run their loops in C. A hand-written loop doing the same job in Python is several times slower.
  4. Batch I/O. Read in large chunks, write once with writelines or a buffered writer, insert rows with executemany or COPY, and send one HTTP request with 500 items instead of 500 requests.
  5. Vectorise. For numeric work on large arrays, NumPy and Polars run the whole operation in C. NumPy Essentials covers why.
  6. Only then reach for parallelism (the previous lesson), or a compiled extension.
Put it in order5 steps

A report job is slow. Put these steps in the order a senior engineer would take them.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Worked case: a slow CSV aggregation

Here is a realistic job. An order export has 30,000 lines. Finance wants revenue per VIP customer for 2026, and the number of distinct SKUs those customers bought. The first version reads cleanly and runs slowly. Profile it:

Python
import cProfileimport csvimport ioimport pstatsimport randomfrom datetime import datetime # A fake export: 30,000 order lines, 4,000 customers, 3,000 SKUs.random.seed(7)buf = io.StringIO()out = csv.writer(buf)out.writerow(["order_id", "customer_id", "sku", "qty", "price", "created_at"])for i in range(30_000): out.writerow([i, f"C{random.randrange(4000)}", f"SKU-{random.randrange(3000)}", random.randint(1, 5), f"{random.uniform(2, 80):.2f}", f"202{random.randint(5, 6)}-{random.randint(1, 12):02d}-01 10:00:00"])CSV_TEXT = buf.getvalue()VIP_IDS = [f"C{n}" for n in range(0, 4000, 2)] # 2,000 VIP customers def is_vip(customer_id): return customer_id in VIP_IDS # a list: scans up to 2,000 items def order_year(created_at): return datetime.strptime(created_at, "%Y-%m-%d %H:%M:%S").year def vip_report(text): revenue = {} skus = [] for row in csv.DictReader(io.StringIO(text)): if not is_vip(row["customer_id"]) or order_year(row["created_at"]) != 2026: continue cid = row["customer_id"] revenue[cid] = revenue.get(cid, 0) + int(row["qty"]) * float(row["price"]) if row["sku"] not in skus: # another list scan skus.append(row["sku"]) return len(revenue), len(skus), round(sum(revenue.values()), 2) profiler = cProfile.Profile()profiler.enable()result = vip_report(CSV_TEXT)profiler.disable()print("result:", result)pstats.Stats(profiler).strip_dirs().sort_stats("tottime").print_stats(6)
Output
Press Run (⌘ Enter) to see what happens.

Read the top rows. is_vip has about half of all the time in its own body: 30,000 scans of a 2,000-item list. Next comes vip_report itself, and its tottime is high for a loop that only does dict updates. That is the hidden row["sku"] not in skus scan, which has no row of its own. Then _strptime: building a full datetime 15,000 times just to read the year.

Now fix one thing at a time, keep the result identical, and time each step:

Python
import csvimport ioimport randomimport timefrom datetime import datetime random.seed(7)buf = io.StringIO()out = csv.writer(buf)out.writerow(["order_id", "customer_id", "sku", "qty", "price", "created_at"])for i in range(30_000): out.writerow([i, f"C{random.randrange(4000)}", f"SKU-{random.randrange(3000)}", random.randint(1, 5), f"{random.uniform(2, 80):.2f}", f"202{random.randint(5, 6)}-{random.randint(1, 12):02d}-01 10:00:00"])CSV_TEXT = buf.getvalue()VIP_LIST = [f"C{n}" for n in range(0, 4000, 2)] def v0_original(text): revenue, skus = {}, [] for row in csv.DictReader(io.StringIO(text)): if row["customer_id"] not in VIP_LIST: continue if datetime.strptime(row["created_at"], "%Y-%m-%d %H:%M:%S").year != 2026: continue cid = row["customer_id"] revenue[cid] = revenue.get(cid, 0) + int(row["qty"]) * float(row["price"]) if row["sku"] not in skus: skus.append(row["sku"]) return len(revenue), len(skus), round(sum(revenue.values()), 2) def v1_sets(text): vips = set(VIP_LIST) # O(1) membership revenue, skus = {}, set() for row in csv.DictReader(io.StringIO(text)): if row["customer_id"] not in vips: continue if datetime.strptime(row["created_at"], "%Y-%m-%d %H:%M:%S").year != 2026: continue cid = row["customer_id"] revenue[cid] = revenue.get(cid, 0) + int(row["qty"]) * float(row["price"]) skus.add(row["sku"]) return len(revenue), len(skus), round(sum(revenue.values()), 2) def v2_no_strptime(text): vips = set(VIP_LIST) revenue, skus = {}, set() for row in csv.DictReader(io.StringIO(text)): if row["customer_id"] not in vips or not row["created_at"].startswith("2026"): continue cid = row["customer_id"] revenue[cid] = revenue.get(cid, 0) + int(row["qty"]) * float(row["price"]) skus.add(row["sku"]) return len(revenue), len(skus), round(sum(revenue.values()), 2) def v3_plain_reader(text): vips = set(VIP_LIST) revenue, skus = {}, set() rows = csv.reader(io.StringIO(text)) next(rows) # skip the header for _, cid, sku, qty, price, created_at in rows: # tuples, no dict per row if cid in vips and created_at.startswith("2026"): revenue[cid] = revenue.get(cid, 0) + int(qty) * float(price) skus.add(sku) return len(revenue), len(skus), round(sum(revenue.values()), 2) def best_of(fn, repeat=3): times = [] for _ in range(repeat): start = time.perf_counter() result = fn(CSV_TEXT) times.append(time.perf_counter() - start) return min(times), result baseline = Noneprint(f"{'version':<18} {'best ms':>8} {'speed-up':>9} result")for fn in (v0_original, v1_sets, v2_no_strptime, v3_plain_reader): seconds, result = best_of(fn) baseline = baseline or seconds print(f"{fn.__name__:<18} {seconds * 1000:8.1f} {baseline / seconds:8.1f}x {result}")
Output
Press Run (⌘ Enter) to see what happens.

On CPython 3.14 on a laptop the table came out like this. The browser is slower, but the ratios are similar:

VersionChangeBest timeSpeed-up
v0original297.8 ms1.0x
v1set for VIPs and SKUs48.4 ms6.2x
v2startswith("2026") instead of strptime19.1 ms15.6x
v3csv.reader with tuple unpacking8.5 ms35.0x

Each step has a lesson. The data structure fix was the biggest, and it scales: at 300,000 rows and 20,000 VIPs the list version gets about a hundred times worse, while the set version only gets ten times slower. The strptime fix is "do not do work you do not need", but it carries a trade-off. strptime also validated the date. startswith trusts the format. That is fine for a machine-generated export with a fixed format. For user input, validate once on the way in, not in the hot loop. The DictReader fix avoids building a dict for every row. It is a smaller, constant-factor win, and it makes the code depend on column order, so it is worth it only in a genuinely hot path.

The result tuple is the same in every row of the table. Never accept a speed-up you have not checked for the same output. A test that compares the old and new function on a sample file is the cheapest insurance there is.

Micro-optimisations, and why they rarely matter

You will see old advice like "copy math.sqrt into a local variable before the loop" or "avoid dots in hot loops". These do still work: a local name is a fast array lookup, while a global or attribute needs a dict lookup. But since 3.11, the specialising adaptive interpreter caches many of those lookups itself, so the gain is often a few percent. That is worth it in the one loop a profiler flagged, after you have fixed the algorithm. It is not worth making ordinary code harder to read.

The same goes for "".join(parts) versus += in a loop, list comprehension versus append, and similar debates. They matter inside a loop that runs millions of times, and nowhere else.

How fast is CPython itself, and what else is there?

CPython 3.11 shipped the biggest speed-up in years from the Faster CPython project: the specialising adaptive interpreter rewrites hot bytecode into versions specialised for the types it actually sees. The official figure was about 1.25x faster on average over 3.10, with large variation by workload. Later releases added smaller gains.

The experimental JIT (PEP 744) exists from 3.13. As of 3.15 it is still experimental and off by default, and its speed-ups so far are modest. Do not plan a project around it. Check the release notes of your version for how to enable it.

PyPy is a separate Python implementation with a mature tracing JIT. It can run long-running pure-Python loops several times faster than CPython. It trails CPython's newest versions, and C extensions run through a compatibility layer that can be slow.

Cython compiles Python-like code with optional C type declarations into a C extension. mypyc compiles ordinary type-annotated Python into a C extension; it is how mypy and Black ship fast builds.

Rust with PyO3 and maturin is the current common choice for a new native hot path. pydantic-core, Polars and orjson are built this way. You write the hot function in Rust, release the GIL inside it, and call it from Python like any module. The cost is a second language and a build step in CI, so reserve it for code that profiling has proved hot and stable.

Key terms
timeit
The standard library module for timing small snippets accurately, with repeats and garbage collection paused.
deterministic profiler
A profiler that records every function call and return, giving exact counts at the cost of overhead; cProfile is one.
sampling profiler
A profiler that inspects the call stack many times per second; low overhead, statistical results, safe on live processes.
tottime
Time spent in a function's own body, excluding the functions it calls.
cumtime
Time from a function's entry to its exit, including everything it called.
flame graph
A chart of sampled call stacks where the width of each bar shows how much time that function was on the stack.
tracemalloc
The standard library tool that records where memory was allocated, with snapshots you can compare to find growth.