Using timeit in Line Magic Mode (%timeit) in Python 2026 with Efficient Code
The %timeit line magic is one of the most convenient tools for quick performance testing in Jupyter Notebooks, IPython, and modern IDEs. In 2026, with faster kernels and improved free-threading support, %timeit remains the fastest way to benchmark small code snippets during development.
This March 15, 2026 guide shows how to use %timeit effectively and interpret its output correctly.
TL;DR — Key Takeaways 2026
%timeitis a Jupyter/IPython magic command that automatically runstimeit- It runs your code multiple times and reports the best time per loop
- Use
-rand-nto control repeats and loops - Perfect for quick comparisons during development
- Free-threading safe and highly accurate in modern Python
1. Basic Usage of %timeit
# Simple timing
%timeit sum(range(100000))
# Timing a list comprehension
%timeit [x**2 for x in range(10000)]
# Timing NumPy operation
import numpy as np
arr = np.arange(100000)
%timeit np.sum(arr**2)
2. Advanced %timeit Options (2026 Recommended)
# Control number of loops and repeats
%timeit -n 1000 -r 7 sum(range(50000))
# Very fast operations - increase loops
%timeit -n 100000 -r 5 x = 42 + 99
# Compare two approaches side by side
data = list(range(10000))
print("List comprehension:")
%timeit [x**2 for x in data]
print("NumPy vectorized:")
import numpy as np
arr = np.array(data)
%timeit arr**2
3. Understanding %timeit Output
Typical Output:
1.23 ms ± 45.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
Breakdown:
1.23 ms→ Best average time per loop± 45.6 µs→ Standard deviation (shows stability)7 runs→ Repeated 7 times1000 loops each→ Each run executed the code 1000 times
4. Best Practices for %timeit in 2026
- Use
-nand-rfor consistent results - Target 0.2 – 2 seconds total runtime per test
- Always compare under the same conditions
- Use cell magic
%%timeitfor multi-line code - Run in a fresh kernel to avoid cache effects
Conclusion — Using %timeit in Line Magic Mode (2026)
%timeit is the quickest and most convenient way to benchmark code during development. In 2026, mastering %timeit with proper -n and -r parameters allows you to make fast, data-driven decisions about code performance directly in your notebook or IDE.
Next steps:
- Start using
%timeit -n 1000 -r 7for all your performance tests - Related articles: Using timeit in Python 2026 • Efficient Python Code 2026