Using timeit in Cell Magic Mode (%%timeit) in Python 2026 with Efficient Code
The %%timeit cell magic is the most convenient way to benchmark multi-line code blocks in Jupyter Notebooks and IPython. In 2026, with improved notebook kernels and free-threading support, %%timeit remains an essential tool for quick and reliable performance testing during development.
This March 15, 2026 guide shows how to use %%timeit effectively for multi-line code and interpret its results correctly.
TL;DR — Key Takeaways 2026
%%timeitis used at the top of a cell to time the entire block of code- It automatically runs the cell multiple times and reports the best time per loop
- Use
-nand-rto control loops and repeats - Perfect for comparing multi-line functions or algorithms
- Free-threading safe and highly accurate in modern Python
1. Basic Usage of %%timeit
%%timeit
total = 0
for i in range(10000):
total += i ** 2
2. Advanced Usage with Options (2026 Recommended)
%%timeit -n 500 -r 7
# Multi-line code block
import numpy as np
arr = np.random.randn(1000, 1000)
result = np.sum(arr**2, axis=1)
mean_val = result.mean()
3. Real-World Comparison Example
# Version 1: Pure Python
%%timeit -n 100 -r 5
total = 0
for i in range(50000):
total += i ** 2
# Version 2: NumPy (much faster)
%%timeit -n 100 -r 5
import numpy as np
arr = np.arange(50000)
result = np.sum(arr**2)
4. Best Practices for %%timeit in 2026
- Place
%%timeitat the very top of the cell - Use
-nand-rfor consistent results (e.g.,-n 200 -r 7) - Target 0.2 – 2 seconds total runtime per test
- Compare multiple versions by running them in separate cells
- Avoid print statements inside the timed cell (they add overhead)
- Include all necessary imports inside the cell or use setup with
-s
Conclusion — Using %%timeit in Cell Magic Mode (2026)
%%timeit is the fastest and most convenient way to benchmark multi-line code blocks directly in your notebook. In 2026, combining it with proper -n and -r options gives you reliable performance insights that help you write significantly more efficient Python code.
Next steps:
- Use
%%timeit -n 200 -r 7for all your multi-line performance tests - Related articles: Using timeit in Python 2026 • Efficient Python Code 2026