Advertisement
Advanced 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?

Short answer

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…

Save Python mock interview
Advertisement
AModel answer
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.py
Real-world example
Pinpointing the EXACT line inside a slow function responsible for most of its execution time, beyond what function-level profiling shows.
Likely follow-ups
  • Why can't you simply 'import' the @profile decorator normally, and what does kernprof do to make it available?
Related topics