Sub topic 9
Zooming in with line-level profiling
This chapter assumes you can read cProfile output (tottime, cumulative, callers), can install packages with pip, and know the basic list, dict, and set trade-offs from earlier chapters. By the end you will be able to profile single functions line by line and tell when the result is trustworthy.
Why function-level profiles sometimes stop short
cProfile reports time per function. That is usually enough, because the fix is often to call a function less often or replace the algorithm. But sometimes the profile points at one function with a high tottime and no obvious culprit. The function may have a loop, a few string operations, a dictionary lookup, and a call to a library. cProfile cannot say which line costs the most.
Line-level profiling answers that. It records, for each line in the functions you select, how many times it ran and how long it took in total. You use it after cProfile has narrowed the search, not instead of it.
Installing line_profiler
The standard tool is the third-party line_profiler package. It provides a LineProfiler class and a command-line runner called kernprof.
pip install line_profilerLine profiling is not in the standard library, so it is not available in a bare interpreter. Install it in your development environment only, not as a dependency of your shipped code.
A first line profile
The example below has a function that removes duplicates from a list of words. It works, but it is slow for large inputs. The script uses the LineProfiler class directly, so you can run it with plain python.
from line_profiler import LineProfiler
def unique_cleaned(words):
result = []
for word in words:
cleaned = word.strip().lower()
if cleaned not in result:
result.append(cleaned)
return result
def make_words(n):
return [f" Word{i % 3000} " for i in range(n)]
if __name__ == "__main__":
words = make_words(20_000)
profiler = LineProfiler()
profiled = profiler(unique_cleaned)
profiled(words)
profiler.print_stats()Calling profiler(unique_cleaned) returns a wrapped version of the function. Only calls through the wrapper are recorded. If you call the original unique_cleaned directly, nothing is measured.
Reading the output
print_stats() prints a table for each profiled function. The numbers on your machine will differ, but the shape looks like this (illustrative values):
Timer unit: 1e-09 s
Total time: 0.31 s
Function: unique_cleaned at line 4
Line # Hits Time Per Hit % Time Line Contents
==============================================================
4 def unique_cleaned(words):
5 1 800 800.0 0.0 result = []
6 20001 2100000 105.0 0.7 for word in words:
7 20000 6500000 325.0 2.1 cleaned = word.strip().lower()
8 20000 298000000 14900.0 96.0 if cleaned not in result:
9 3000 900000 300.0 0.3 result.append(cleaned)
10 1 400 400.0 0.0 return resultThe columns mean:
| Column | Meaning |
|---|---|
| Hits | How many times the line ran |
| Time | Total time spent on the line, in timer units shown in the header |
| Per Hit | Time divided by hits |
| % Time | Share of the function's total time |
| Line Contents | The source line |
Read the table in this order:
- Find the line with the largest
% Time. Here it is the membership testcleaned not in result. - Check
Hitsto see whether the line is expensive per call or simply called often. Line 8 has a highPer Hitas well as 20,000 hits, because each test scans a list. - Ask why. A
not incheck on a list is a linear scan, so the loop is quadratic in the number of distinct values.
The profile did not tell you the answer. It told you where to look, and your knowledge of data structures supplied the diagnosis.
Applying the fix and checking it
The fix is the one from the data-structures chapter: track seen values in a set, and keep the list only to preserve order.
from line_profiler import LineProfiler
def unique_cleaned_fast(words):
seen = set()
result = []
for word in words:
cleaned = word.strip().lower()
if cleaned not in seen:
seen.add(cleaned)
result.append(cleaned)
return result
def make_words(n):
return [f" Word{i % 3000} " for i in range(n)]
if __name__ == "__main__":
words = make_words(20_000)
profiler = LineProfiler()
profiled = profiler(unique_cleaned_fast)
profiled(words)
profiler.print_stats()Run it and compare. The membership line should no longer dominate. Now the strip().lower() line and the loop overhead take the largest share, which is expected. The remaining work is real work.
Always confirm the end-to-end gain with timeit or perf_counter on the unprofiled function. Line profiling slows the code, so its absolute times are not the speed your users see.
Using kernprof on a script
For larger scripts, kernprof avoids editing the code to build wrappers. You mark functions with @profile, then let kernprof inject that name at run time.
@profile
def unique_cleaned(words):
result = []
for word in words:
cleaned = word.strip().lower()
if cleaned not in result:
result.append(cleaned)
return result
words = [f" Word{i % 3000} " for i in range(20_000)]
unique_cleaned(words)Save this as dedupe.py and run:
kernprof -l -v dedupe.pyThe -l flag selects line-by-line profiling, and -v prints the report when the script ends. kernprof also saves the results to dedupe.py.lprof. You can view them again later without rerunning the script:
python -m line_profiler dedupe.py.lprofChoosing what to profile
Line profiling only records functions you ask it to record. That is a feature, since tracing every line of a program would be slow and the report would be unreadable. Some practical rules follow.
- Start with one function, the top
tottimeentry from cProfile. Add more only when the first report points at a call into another of your functions. - A line that calls a function shows the total time of that call, but not what happened inside it. To look inside, profile that function too. With the class API,
profiler.add_function(other_func)registers a function without wrapping the call site. - A function with a large
cumulativetime but smalltottimeis usually a caller. Its own lines are cheap, and its callees are where the time goes. Profile the callees instead. - Functions that run for microseconds but are called millions of times are poor candidates. The profiling overhead per line can exceed the work itself.
What line profiling gets wrong
Treat the results as relative, not absolute.
- Overhead is per line. The profiler adds a fixed cost on every line event. Code made of many cheap lines (tight loops with small bodies) looks slower than it is, and those lines get an inflated
% Time. Code made of a few expensive lines (a big NumPy call, a database query) is less distorted. - Timing can differ from reality. A change that looks like a win in the profile can disappear in an unprofiled run. Always re-time without the profiler.
- Hits are exact, time is not. Trust
Hitsas a precise count. TreatTimeas approximate, especially for lines under about a microsecond. - Multi-line statements are attributed to their first line (or spread oddly). For a long comprehension or chained expression, split it temporarily into several statements to see which part is slow.
- Compiled code is a single block. A line such as
np.sort(arr)shows one number. Line profiling cannot show what happens inside C code. For that you need a different tool, such as a sampling profiler or a native profiler. - Threads and processes are not combined. Profiling records the code that ran in the profiled thread. Work in worker processes does not appear in the parent's report.
A short checklist
- Run cProfile first and note the function with the highest
tottime. - Line-profile only that function.
- Identify the line with the highest
% Time, then check itsHitsandPer Hit. - Decide whether the cause is the algorithm, the data structure, or repeated work, and fix that.
- Re-time without the profiler and compare to your baseline.
- Remove
@profiledecorators and profiling code before merging.
Exercise
A line-profile of a function shows line 12 (total += lookup[key]) with 2,000,000 hits and 4% of the time, while line 15 (rows = sorted(rows)) has 1 hit and 70% of the time. Which line is the better target, and what should you check before and after changing it?
Show answer
Line 15 is the better target, because it takes 70% of the function's time even though it runs once. The sort is probably a large call whose cost depends on the size of rows. Before changing it, record a baseline with timeit or perf_counter on the unprofiled function. After changing it (for example, avoiding the sort, sorting less data, or using heapq.nsmallest if only a few items are needed), re-time without the profiler and compare. Line 12 has many hits, but its share of the time is only 4%, so even making it free would gain very little.
Exercise
You run python myscript.py after adding @profile above a function and get NameError: name 'profile' is not defined. Give two ways to fix it.
Show answer
Run the script with kernprof -l -v myscript.py, which injects profile into the builtins. Or remove the decorator and use LineProfiler from the line_profiler package in code: create LineProfiler(), wrap the function with it, call the wrapper, then call print_stats().