Accelerating Python code with Numba
When it is too difficult or impossible to vectorize an algorithm, you often need to use Python loops. However, Python loops are slow. Fortunately, Numba provides a Just-In-Time (JIT) compiler that can compile pure Python code straight to machine code thanks to the LLVM compiler architecture. This can result in massive speedups.
In this section, we'll see how to use Numba to accelerate a mathematical modeling simulation.
To install numba, just type conda install numba
on the command-line.
Let's first import a few packages:
In [1]: import math import random import numpy as np from numba import jit, vectorize, float64 import matplotlib.pyplot as plt import seaborn %matplotlib inline
Random walk
We will simulate a random walk with jumps. A particle is on the real line, starting at 0. At every time step, the particle makes a step to the right or to the left. If the particle crosses a threshold, it is reset at its...