Python › Debugging & Profiling
How would you use line_profiler (a third-party tool) to get LINE-BY-LINE timing information within a specific function, more granular than cProfile's function-level data?
AdvancedAnswer
Decorate the target function with @profile (line_profiler's marker decorator) and run the script with `kernprof -l -v script.py` — this produces a report showing the exact TIME SPENT on EACH INDIVIDUAL LINE within that function, pinpointing precisely which line (not just which function) is the actual bottleneck.
@profile # requires running via kernprof, not a normal Python run
def process_data(data):
cleaned = [x.strip() for x in data] # line-level timing shown for THIS line
filtered = [x for x in cleaned if x] # and separately for THIS line
return sorted(filtered)
# Run with: kernprof -l -v script.pyReal-world example Pinpointing the EXACT line inside a slow function responsible for most of its execution time, beyond what function-level profiling shows.