Sub topic 9
Zooming in with line-level profiling
This chapter assumes you can run cProfile and read its output, as covered earlier. You should also be comfortable installing packages with pip and editing a Python module.
Why function-level profiles are not enough
cProfile reports time per function. Once it points to a function that dominates the run, you still don't know which lines inside it are slow. A line-level profiler fills that gap. It records how many times each line ran and how long it took.
The usual tool is line_profiler, a third-party package. Install it with pip:
pip install line_profilerUse it second. Run cProfile first to find the hot function, then point the line profiler at only that function. Line-level tracing adds overhead to every line, so profiling a whole program this way is slow and its numbers are noisy.
A worked example
The function below looks for words that appear more than once in a list. It has a hidden cost on one line.
Save it as dupes.py:
@profile
def find_duplicates(words):
seen = []
duplicates = []
for word in words:
if word in seen:
if word not in duplicates:
duplicates.append(word)
else:
seen.append(word)
return duplicates
if __name__ == "__main__":
data = [str(i % 3_000) for i in range(20_000)]
print(len(find_duplicates(data)))The @profile decorator is not imported. The kernprof command injects it at run time, which is why the script fails if you run it with plain python. Run it like this:
kernprof -l -v dupes.pyThe -l flag turns on line-by-line mode. The -v flag prints the report when the script ends.
Reading the report
The report has one row per line of the decorated function. These are the columns:
| Column | Meaning |
|---|---|
| Line # | Line number in the file |
| Hits | How many times the line ran |
| Time | Total time spent on the line, in timer units |
| Per Hit | Average time per execution |
| % Time | Share of the function's total time |
| Line Contents | The source line |
Look at % Time first, then at Hits. In this example the line if word in seen: takes most of the time. It runs 20,000 times, and each run scans a list. That is a linear search inside a loop, which makes the function quadratic.
The cause is a data structure choice, not a Python trick. Switching seen and duplicates to sets makes each membership test constant time on average:
def find_duplicates(words):
seen = set()
duplicates = set()
for word in words:
if word in seen:
duplicates.add(word)
else:
seen.add(word)
return list(duplicates)Note that the result order can differ from the list version, because sets are unordered. Check whether callers depend on order before you make this change.
Common errors
- NameError: name 'profile' is not defined. You ran the script with
pythoninstead ofkernprof. Run it throughkernprof, or remove the decorator. - Profiling too many functions. Each decorated function adds overhead. Decorate only the one or two suspects.
- Trusting absolute times. Tracing slows the code, so compare
% Timebetween lines. Usetimeitorperf_counteron the undecorated code to confirm the real speedup. - Stopping at the hot line. A high
Hitscount may mean the loop itself is the problem, not the line. Ask whether the work should happen that many times at all.
Check your understanding
Exercise
A line-level report shows that total = total + compute(x) has 1,000,000 hits and 2% of the time, while if x in items: has 1,000,000 hits and 90% of the time, where items is a list. What is the most likely fix, and how do you confirm it worked?
Show answer
The membership test scans the list on every iteration. Convert items to a set before the loop so each test is a constant-time lookup on average. Confirm by timing the function before and after with timeit or time.perf_counter on the undecorated code, and check that the output is unchanged.