Speeding up a Python loop with Numba JIT

MediumGPU accelerationAccelerating computation

Goal: Compiling a numerical function to machine code with a single decorator.

Python — example.py
import time, numpy as np
from numba import njit

def pairwise_py(X):
    n = X.shape[0]; out = 0.0
    for i in range(n):
        for j in range(i + 1, n):
            out += np.sqrt(((X[i] - X[j]) ** 2).sum())
    return out

fast = njit(pairwise_py)
X = np.random.default_rng(0).random((400, 3))
fast(X[:5])                                  # warm-up (compilation)
t = time.perf_counter(); a = pairwise_py(X); t_py = time.perf_counter() - t
t = time.perf_counter(); b = fast(X); t_nb = time.perf_counter() - t
print("The two results match:", np.isclose(a, b))
print(f"Python: {t_py:.3f}s | Numba: {t_nb:.4f}s | speed-up ≈ {t_py / t_nb:.0f}×")

Code explanation

@njit compiles the function on its first call (so we call it once to warm up), after which the loop runs at close to C speed. We compare the time with the original version; the figure varies by machine.

Requirements

Shell
pip install numba numpy

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

The two results match: True
Python: 0.120s | Numba: 0.0044s | speed-up ≈ 27×

This example was actually run and tested on 21 November 2026 on a CPU — numba 0.68.1, numpy 2.5.5, python 3.13.18

Libraries used

Related examples

ResearchTriton LanguageNot run in the test environment

A vector addition kernel in Triton

Writing a GPU kernel in Python instead of CUDA C++.

GPU acceleration · Custom GPU kernels