Your script that checks 5,000 students' registrations takes several seconds, and you want it faster. The tempting move is to start rewriting the part that looks slow. Experienced programmers don't guess, because guesses are usually wrong: the slow part is often one innocent-looking line. Instead, they profile: they run the program under a tool that measures where the CPU time actually goes, then fix the single biggest cost.
CPU profiling means measuring how much processor time each function (or line) of a program uses. This lesson covers the difference between wall time and CPU time, quick timing with time and timeit, Python's built-in profiler cProfile, sampling profilers like py-spy, how to read a flame graph, and a worked example that finds and fixes a hotspot.
What you need first: Python functions and threads, multithreading and multitasking. Big-O notation helps explain the fix.
Key terms
- Profiler: a tool that measures where a program spends its time (or memory).
- Hotspot (bottleneck): the small part of the code that uses most of the time.
- Wall-clock time: real elapsed time, as a stopwatch would measure, including waiting.
- CPU time: time the CPU actually spent running your code, excluding waiting for disks, networks or sleep.
- Deterministic (tracing) profiler: records every function call and return. Exact counts, but slows the program down.
- Sampling profiler: checks what the program is doing many times a second. Low overhead, approximate results.
- Flame graph: a picture of profiling results, where wider bars mean more time spent.
Measure first
Most programs spend most of their time in a small part of their code; a rough rule says about 80% of the time is spent in 20% of the code, and often it's far more lopsided. Speeding up anything else makes no visible difference. So the order is always:
- Measure how long the whole thing takes.
- Profile to find the hotspot.
- Fix that one part (usually a better algorithm or data structure).
- Measure again to confirm it helped, and that the output is still correct.
Wall time vs CPU time
| Wall-clock time | CPU time | |
|---|---|---|
| Measures | Real time from start to finish | Time the CPU spent on your code |
Includes waiting for network, disk, sleep | Yes | No |
| Python function | time.perf_counter() | time.process_time() |
| Tells you | How long the user waits | How much computing work you did |
import time
wall_start, cpu_start = time.perf_counter(), time.process_time()
time.sleep(0.5) # waiting: wall time only
total = sum(i * i for i in range(2_000_000)) # computing: wall and CPU time
wall = time.perf_counter() - wall_start
cpu = time.process_time() - cpu_start
print("wall time over 0.5 s:", wall > 0.5)
print("CPU time well under wall time:", cpu < wall - 0.4)
wall time over 0.5 s: True
CPU time well under wall time: True
The half-second sleep shows up in wall time but not CPU time. If a slow program's CPU time is small, it's waiting (network, disk, database), and a CPU profiler won't help much; look at the slow calls it waits on, or use threads or asyncio (threads and multitasking). If CPU time is close to wall time, the program is CPU-bound, and profiling is the right tool.
We print checks instead of the actual times, because timings differ on every computer and every run.
Quick timing: timeit
To compare two small pieces of code, Python's timeit runs each many times and reports the total:
import timeit
as_list = list(range(10_000))
as_set = set(as_list)
list_time = timeit.timeit(lambda: 9_999 in as_list, number=1_000)
set_time = timeit.timeit(lambda: 9_999 in as_set, number=1_000)
print("set lookup at least 50 times faster:", list_time > 50 * set_time)
set lookup at least 50 times faster: True
Checking in on a list looks at items one by one (O(n)); a set uses a hash table and jumps straight to the answer (about O(1)). The gap grows with the size of the data. In a terminal, python -m timeit "sum(range(1000))" does the same from the command line.
timeit is for comparing small snippets. To find which part of a whole program is slow, you need a profiler.
Profiling Python with cProfile
cProfile is Python's built-in deterministic profiler. The easiest way to use it is from the terminal:
python -m cProfile -s cumulative app.py
It runs app.py and prints a table of every function called, sorted by cumulative time. The columns:
| Column | Meaning |
|---|---|
ncalls | How many times the function was called |
tottime | Time spent in the function itself, not counting functions it called |
percall | tottime divided by ncalls |
cumtime | Time in the function including everything it called |
filename:lineno(function) | Which function |
How to read it: high cumtime shows which top-level path is slow; high tottime shows where the work is actually done. A function called thousands of times with a small percall can still be the hotspot.
A worked example
A registration check: for each of 5,000 roll numbers, is it in the list of registered students?
import cProfile
import pstats
def is_registered(roll, registered):
return roll in registered
def count_registered(rolls, registered):
return sum(1 for r in rolls if is_registered(r, registered))
def main(registered):
rolls = list(range(5_000))
return count_registered(rolls, registered)
registered = list(range(0, 20_000, 2)) # 10,000 even roll numbers
profiler = cProfile.Profile()
profiler.enable()
result = main(registered)
profiler.disable()
stats = pstats.Stats(profiler)
calls = {name: data[1] for (_, _, name), data in stats.stats.items()}
total_time = stats.total_tt
lookup_time = next(data[2] for (_, _, name), data in stats.stats.items() if name == "is_registered")
print("registered:", result)
for name in ("main", "count_registered", "is_registered"):
print(f"{name}: called {calls[name]} time(s)")
print("is_registered uses most of the time:", lookup_time > total_time / 2)
registered: 2500
main: called 1 time(s)
count_registered: called 1 time(s)
is_registered: called 5000 time(s)
is_registered uses most of the time: True
stats.stats holds the raw numbers for each function: data[1] is the call count and data[2] is tottime. Usually you'd just call stats.sort_stats("cumulative").print_stats(10) to print the top 10 rows; we pull out the parts that are the same on every machine.
The profile points straight at is_registered: it's called 5,000 times, and each call scans a 10,000-item list. That's up to 5 crore comparisons. The fix is a better data structure, not faster code around it:
import time
def count_registered(rolls, registered):
return sum(1 for r in rolls if r in registered)
rolls = list(range(5_000))
registered_list = list(range(0, 20_000, 2))
registered_set = set(registered_list)
start = time.perf_counter()
slow = count_registered(rolls, registered_list)
list_time = time.perf_counter() - start
start = time.perf_counter()
fast = count_registered(rolls, registered_set)
set_time = time.perf_counter() - start
print("same answer:", slow == fast)
print("set version at least 20 times faster:", list_time > 20 * set_time)
same answer: True
set version at least 20 times faster: True
One changed line (set(...)), checked for the same answer, and measured again. That's the whole profiling loop.
Sampling profilers
cProfile records every call, which slows the program (sometimes by 2 times or more) and can exaggerate the cost of small, frequently called functions. Sampling profilers take a different approach: many times a second, they look at what the program is doing right now and count where it is. Functions that show up in more samples use more time.
| Tool | Language / system | Notes |
|---|---|---|
| py-spy | Python | Attaches to a running program without changing it; can draw flame graphs. Install with pip |
| Scalene | Python | Splits time into Python vs native code, and also profiles memory |
| line_profiler | Python | Times each line of chosen functions (deterministic) |
| perf | Linux, any compiled language | The standard Linux CPU profiler |
| Visual Studio / Windows Performance Analyzer | Windows | Profilers for Windows programs |
| Instruments | macOS | Apple's profiling tools, part of Xcode |
| Browser DevTools, Performance tab | JavaScript in web pages | Records and shows a flame chart of a page's activity |
Sampling profilers are safe to use on real, running systems, which is why they're popular for profiling servers in production.
Reading a flame graph
A flame graph shows a profile as stacked bars:
- Each bar is a function. The bar above it is a function it called; the bottom bar is where the program started. (It's the call stack from stack and heap memory, stacked upwards.)
- A bar's width is the share of samples, so the share of time, spent in that function and the functions it called.
- Left-to-right order is usually alphabetical, not time order.
Look for wide bars near the top: functions that use a lot of time themselves, not just by calling others. In our example, is_registered would be a wide bar sitting on count_registered, which sits on main.
[ is_registered ]
[ count_registered ]
[ main ]
Common causes of slow code
Profiles keep pointing at the same few kinds of problem:
| Cause | Example | Usual fix |
|---|---|---|
| Wrong data structure | in on a big list inside a loop | Use a set or dictionary |
| Repeated work | Recomputing the same value in every loop pass | Compute once before the loop, or cache it (functools.lru_cache) |
| Nested loops over big data | Comparing every item with every other | A better algorithm, often with a dictionary |
| Python loops over numbers | Adding up a million values in a for loop | NumPy or pandas, which loop in C |
| Too many small I/O calls | Writing a file one line at a time with a flush each time | Batch the writes |
| String building in a loop | s += piece many times | Collect pieces in a list, then "".join(pieces) |
Most real speed-ups come from the first three rows: a better algorithm or data structure beats any amount of small tweaking.
Practice
- A script takes 10 seconds of wall time but only 0.4 seconds of CPU time. Where is the time going, and will a CPU profiler help much?
Show the answer
It's mostly waiting: on the network, the disk, a database, or sleep. A CPU profiler shows little because the CPU is idle. Look at what it waits for, and consider doing the waits at the same time with threads or asyncio.
- In a
cProfiletable, functionparsehasncalls1,tottime0.01 s andcumtime8 s. What does that tell you?
Show the answer
parse itself does almost no work (0.01 s), but the functions it calls take nearly 8 seconds. Look further down the call tree, at the functions parse calls, for the real hotspot.
- Why do we print checks like
Trueinstead of the actual times in these examples?
Show the answer
Timings change between computers, between runs, and with whatever else is running. The comparison (which is faster, and by roughly how much) stays the same, so that's what we check.
- Use
timeitto check whether"".joinis faster than+=for joining 10,000 short strings, printing only a True/False comparison.
Show the answer
import timeit
pieces = ["ab"] * 10_000
def with_plus():
s = ""
for p in pieces:
s += p
return s
def with_join():
return "".join(pieces)
print(with_plus() == with_join())
print("join is faster:", timeit.timeit(with_join, number=200) < timeit.timeit(with_plus, number=200))
True
join is faster: True
Check the results are equal first, then compare the times.
- In a flame graph, bar A is very wide but the bars on top of it cover almost all of its width. Bar B is narrower but has nothing on top of it. Which function is doing the work itself?
Show the answer
B. A is wide because of the functions it calls (the bars on top), not its own work. B's whole width is its own time, so it's the better place to look for a fix.
Interview questions
What is the difference between a sampling profiler and an instrumenting profiler?
An instrumenting (deterministic) profiler records every function entry and exit, giving exact call counts and times but adding overhead that can distort results. A sampling profiler periodically records the current call stack; it has low overhead and is safe in production, but results are statistical and can miss very short functions.
How would you find out why a Python program is slow?
Measure the total wall and CPU time to see whether it's CPU-bound or waiting on I/O. If CPU-bound, run cProfile or a sampling profiler like py-spy, sort by cumulative and total time, and find the hotspot. Fix it, usually with a better algorithm or data structure, check the output is unchanged, and measure again. For I/O-bound code, look at the slow external calls and consider concurrency.
What is the difference between tottime and cumtime in cProfile?
tottime is the time spent inside the function's own code, excluding calls to other functions. cumtime includes time spent in all functions it called. High cumtime with low tottime means the cost is in its callees.
Key takeaways
- Don't guess what's slow: measure, profile, fix the biggest hotspot, then measure again and check the output.
- Wall time includes waiting; CPU time doesn't. A big gap means the program is waiting on I/O, not computing.
timeitcompares small snippets;cProfile(python -m cProfile -s cumulative app.py) finds the hotspot in a whole program.- Sampling profilers (py-spy, perf) have low overhead and suit running systems; flame graphs show where time goes, with width as time.
- Most big speed-ups come from better data structures and algorithms, such as a set instead of a list for lookups.
Frequently asked questions
What is CPU profiling?
Measuring how much processor time each function or line of a program uses, so you can find the parts that make it slow. Profilers do this by recording every call, or by sampling what the program is doing many times a second.
Is cProfile accurate?
Its call counts are exact. Its times are good for finding hotspots, but its overhead makes small, frequently called functions look more expensive than they really are. Confirm a suspected hotspot with a sampling profiler or by timing the fix.
What is the difference between profiling and benchmarking?
Benchmarking measures how fast something is overall, often to compare versions or machines. Profiling measures where the time goes inside a program, so you know what to change.
What to learn next
- Learn why the set was so much faster in Big-O notation.
- Revise the call stack that profilers show in stack and heap memory.
- Choose the right structure for fast code with choosing the right Python data structure.