Understanding %lprun Output in Python 2026 with Efficient Code
The %lprun magic from line_profiler is one of the most powerful tools for line-by-line performance analysis. In 2026, understanding its output correctly is essential for identifying exact bottlenecks and making targeted optimizations in your Python code.
This March 15, 2026 guide explains how to read and interpret %lprun output effectively.
TL;DR — Key Takeaways 2026
%lprunshows execution time per line of code- Focus on Time and Per Hit columns
- High % Time indicates the real hotspots
- Use it after
cProfileto zoom into slow functions - Free-threading safe and highly accurate in modern Python
1. How to Use %lprun
%load_ext line_profiler
def slow_function(n=10000):
total = 0
for i in range(n):
total += i ** 2
return total
# Run line profiler
%lprun -f slow_function slow_function()
2. Understanding %lprun Output
Typical Output:
Timer unit: 1e-06 s
Total time: 0.012345 s
File: example.py
Function: slow_function at line 1
Line # Hits Time Per Hit % Time Line Contents
==============================================================
1 def slow_function(n=10000):
2 1 5.0 5.0 0.0 total = 0
3 10001 8234.0 0.8 66.7 for i in range(n):
4 10000 4106.0 0.4 33.3 total += i ** 2
5 1 0.0 0.0 0.0 return total
Key Columns:
- Hits — How many times the line ran
- Time — Total time spent on that line (microseconds)
- Per Hit — Average time per execution
- % Time — Percentage of total function time (most important!)
3. Best Practices for Reading %lprun Output
- Focus on lines with highest % Time
- High Hits + low Per Hit = many cheap operations (good candidate for vectorization)
- Low Hits + high Per Hit = expensive operations (look for I/O or heavy calculations)
- Always compare before and after optimization
Conclusion — Understanding %lprun Output in 2026
%lprun gives you line-level visibility into your code’s performance. In 2026, mastering this tool allows you to find and fix bottlenecks with surgical precision, leading to much faster and more efficient Python applications.
Next steps:
- Install
line_profilerand start using%lprunon your slowest functions - Related articles: Code Profiling for Runtime 2026 • Efficient Python Code 2026