Moving a NumPy computation to the GPU with CuPy
Running NumPy-style code on the GPU.
Goal: Compiling a numerical function to machine code with a single decorator.
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}×")
@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.
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
Running NumPy-style code on the GPU.
Writing a GPU kernel in Python instead of CUDA C++.
Sections
No section has this name. Press “Search” to search all site content.
Favourites
My results & certificates
My academy progressMy quiz resultsKids’ progressAcademy certificatesQuiz certificatesStart any lesson or quiz and it will show up here so you can get back to it quickly.
Settings
I am the AI Frameworks & Libraries Assistant. Describe your project or ask me about a library, a comparison or a code example, and I will answer from the encyclopedia's database with links and sources.
Answers from the encyclopedia's database only, without a language model and without sending your question to any third party.
The assistant can make mistakes, so check the attached sources.