Phase 20 of 25 · Topic 20.3

Numba JIT Compiler (@jit / @njit High-Speed Loops)

1Concept

Numba is a Just-In-Time (JIT) compiler for numeric Python. Using LLVM, `@njit` compiles Python numerical functions directly into machine code on first invocation, matching native C/Fortran performance.

2Architecture Diagram

Python Loop (Slow) ---> [ Numba LLVM JIT Compiler ] ---> Native CPU Vectorized Assembly (Instant!)

3Code Example

Python 3.12
# Numba JIT pattern
numba_sample = '''
from numba import njit
import numpy as np

@njit(fastmath=True)
def compute_mandelbrot(size: int, iterations: int):
    # Compiles to native LLVM machine assembly on first call!
    grid = np.zeros((size, size))
    for i in range(size):
        for j in range(size):
            grid[i, j] = (i * j) % iterations
    return grid
'''
print("=== Numba JIT Architecture ===")
print(numba_sample.strip())

4Expected Output

=== Numba JIT Architecture ===
from numba import njit
import numpy as np

@njit(fastmath=True)
def compute_mandelbrot(size: int, iterations: int):
    # Compiles to native LLVM machine assembly on first call!
    grid = np.zeros((size, size))
    for i in range(size):
        for j in range(size):
            grid[i, j] = (i * j) % iterations
    return grid

5Key Takeaways

  • `@njit` (no-python mode) guarantees code runs 100% in machine code without CPython interpreter fallback.
  • First function invocation experiences a slight compilation latency; subsequent runs execute instantly.
  • `fastmath=True` enables aggressive floating-point optimizations (SIMD vectorization).