Using timeit in Line Magic Mode (%timeit) in Python 2026 with Efficient Code

Efficient Code Mar 15, 2026

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

  • %timeit is a Jupyter/IPython magic command that automatically runs timeit
  • It runs your code multiple times and reports the best time per loop
  • Use -r and -n to 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 times
  • 1000 loops each → Each run executed the code 1000 times

4. Best Practices for %timeit in 2026

  • Use -n and -r for consistent results
  • Target 0.2 – 2 seconds total runtime per test
  • Always compare under the same conditions
  • Use cell magic %%timeit for multi-line code
  • Run in a fresh kernel to avoid cache effects

How the %timeit Magic Works

%timeit is an IPython and Jupyter line magic. It wraps the timeit module, chooses the number of loops automatically, repeats the measurement seven times by default, and prints the mean and standard deviation per loop.

Because it is a magic command, it only works inside IPython or Jupyter, not in a plain .py script. In scripts, use timeit.repeat with the same idea.

Use -n to set loops per run, -r to set the number of runs, and -o to return a result object you can store and compare.

Worked Example: The Script Equivalent of %timeit

This plain Python snippet reproduces what %timeit reports, so the measurement can run in scripts and CI.

import statistics
import timeit

stmt = "sum(range(100_000))"
timer = timeit.Timer(stmt)
number, _ = timer.autorange()
runs = [t / number for t in timer.repeat(repeat=7, number=number)]

mean = statistics.mean(runs)
stdev = statistics.stdev(runs)
print(f"{mean * 1e6:.1f} µs ± {stdev * 1e6:.1f} µs per loop "
      f"(mean ± std. dev. of 7 runs, {number} loops each)")

The printed line has the same structure as the %timeit summary: mean and standard deviation per loop over seven runs. Numbers will differ by machine, but the method is the same.

Practical Tips

In a notebook, the result object returned with -o has attributes such as best, average and all_runs, so you can store several measurements and compare them in later cells.

Common Mistakes

  • Using %timeit in a .py file.
  • Timing code that depends on cell state changed by the timing itself.
  • Comparing results from different machines.
  • Ignoring a large standard deviation.

Quick Summary

  • %timeit is an IPython line magic.
  • It reports mean ± std over seven runs.
  • Use -n, -r and -o for control.
  • Use timeit.repeat in plain scripts.

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 7 for all your performance tests

Related Tutorials

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices