Skip to content
VLASIFY™
GuideHPC, GPU & Linux

How to speed up Python code for scientific computing

Updated · Scientifically reviewed by Dinkar Mishra, PhD on

Short answer

Measure before optimising: profile with cProfile or line_profiler to find the few lines that take most of the time. Then, in order of effort: use a better algorithm or library routine, replace Python loops with NumPy array operations, compile remaining loops with Numba, avoid unnecessary copies and I/O, and only then parallelise (multiprocessing, MPI) or move to a GPU (CuPy, PyTorch, JAX). Check that results stay identical at each step.

Who this is for

Scientists and engineers whose Python analysis or simulation scripts are too slow, from students to research software engineers.

Software

Python ≥ 3.9NumPy ≥ 1.22Numba ≥ 0.57

How it works

Python executes each operation through the interpreter, which makes tight numerical loops slow. Fast scientific Python moves the inner loops into compiled code: NumPy’s C routines, Numba-compiled functions, or GPU kernels. The skill is finding which loops matter and choosing the cheapest way to move them.

Step 1: profile

python -m cProfile -s cumtime analysis.py | head -n 25

For line-by-line timing of a suspect function, decorate it with @profile and run kernprof -l -v analysis.py (from the line_profiler package). Typically one or two functions dominate; optimise only those.

Step 2: better algorithms and library routines

Before micro-optimising, ask whether a library already does it in compiled code: scipy.integrate, scipy.spatial.cKDTree for neighbour searches, np.fft, scipy.sparse solvers. An O(N²) to O(N log N) improvement beats any constant-factor speedup.

Step 3: vectorise with NumPy

import numpy as np

x = np.random.default_rng(0).random(1_000_000)

# Slow: a Python loop
total = 0.0
for v in x:
    total += v * v

# Fast: one vectorised expression (runs in compiled code)
total_vec = np.dot(x, x)

Use boolean masks instead of if inside loops, broadcasting instead of nested loops, and in-place operations (out= arguments, +=) to avoid temporaries.

Step 4: compile loops with Numba

When the logic is a genuine loop, as in this leapfrog particle push with periodic wrapping, Numba compiles it:

import numpy as np
from numba import njit


@njit(cache=True)
def push(x, v, E, dt, qm, L):
    for i in range(x.size):
        v[i] += qm * E[i] * dt
        x[i] += v[i] * dt
        if x[i] >= L:
            x[i] -= L
        elif x[i] < 0.0:
            x[i] += L


x = np.random.default_rng(1).random(1_000_000)
v = np.zeros_like(x)
E = np.ones_like(x)
push(x, v, E, 0.01, -1.0, 1.0)   # first call compiles; later calls run at compiled speed

Add parallel=True and numba.prange to spread independent iterations across cores.

Step 5: memory and I/O

  • Use float32 where the accuracy is sufficient: half the memory traffic.
  • Read binary formats (HDF5, NumPy .npy, Parquet) instead of parsing text in loops.
  • Keep arrays contiguous, and avoid repeated conversion between lists and arrays.

Step 6: parallelise or accelerate

Once single-core code is efficient:

Checking that it is still correct

After every optimisation, compare outputs with the original version on a test input (np.allclose(old, new, rtol=1e-12) or an appropriate tolerance). Faster but wrong code is a regression. Changes in summation order and precision can change the last digits legitimately; decide your tolerance in advance.

Assumptions and limitations

  • Speedups depend on the problem, data size and hardware. Measure with timeit or the profiler, not by expectation.
  • Numba supports a subset of Python and NumPy. Unsupported features fall back to errors in @njit (nopython) mode.
  • For very large production codes, a compiled core with a Python interface may ultimately be the maintainable choice; our research software engineering service helps decide.

Frequently asked questions

How much faster is NumPy than a Python loop?+

For simple arithmetic over large arrays, vectorised NumPy is often tens to hundreds of times faster than an equivalent pure-Python loop, because the loop runs in compiled code. The gain depends on the operation and array size; measure it for your case with timeit.

When should I use Numba instead of NumPy?+

When the algorithm is naturally a loop with dependencies or branches (particle pushers, stencils with conditions, recurrences), or when vectorising would create large temporary arrays. Numba compiles the loop to machine code and often matches C speed.

Should I rewrite my code in C++ or Fortran?+

Rarely as a first step. NumPy, SciPy and Numba cover most needs with far less effort. Rewriting core kernels in a compiled language makes sense for long-lived production codes, often exposed to Python via pybind11 or f2py.

Why is my code still slow after vectorising?+

Common causes: repeated allocation of temporaries, converting between lists and arrays inside loops, I/O in the inner loop, or an algorithm with poor complexity (for example O(N²) neighbour searches where a tree or grid would be O(N log N)).

References

  1. The Python profilers (cProfile) · Python documentation
  2. NumPy user guide: broadcasting and vectorisation · NumPy
  3. Numba documentation: 5-minute guide · Numba
  4. line_profiler · line_profiler project

Need help applying this?

Our physicists turn concepts into working, verified simulations for research groups and companies.

Services listed on this page are available today. Products marked “early access” or “in development” on our platform page are not yet generally available.

Spotted an error or an outdated command? Tell us. We correct verified issues promptly.

Related guides

How Vlasify can help

Get a Quote