This exercise builds on #54. It is part of a series that looks at execution time of different ways to calculate π using the same Monte Carlo approach.
This exercise uses Numba and Cython to accomplish this approximation of π. A Numba version of the code is already written, and you can find it in calc_pi_numba.py file in the pi_calculation repository, on the class branch. Your job is measure how much time it takes to complete in comparison to #46.
Preparation
The two frameworks we will look at allow you to write Python-looking code and compile it into more efficient code which should run faster. Numba is a compiler for Python array and numerical functions. Cython is a way to program C extensions for Python using a syntax similar to Python.
Both frameworks should come with your conda installation. If not, and you get errors when running the instructions below, use conda or pip to install them (see their websites linked above for instructions).
Discuss how different it looks to the original. Is it more/less readable? Can you understand what the differences mean?
Run the code with python calc_pi_numba.py. How does the time compare to the original?
Using Cython
Next, try to use Cython to approximate π. This part will be easier for users of Linux and macOS, as getting Cython to run on Windows is a little more involved.
We will use a notebook for this example, as it lets us see more information about how Cython works.
This exercise builds on #54. It is part of a series that looks at execution time of different ways to calculate π using the same Monte Carlo approach.
This exercise uses Numba and Cython to accomplish this approximation of π. A Numba version of the code is already written, and you can find it in
calc_pi_numba.py
file in the pi_calculation repository, on theclass
branch. Your job is measure how much time it takes to complete in comparison to #46.Preparation
The two frameworks we will look at allow you to write Python-looking code and compile it into more efficient code which should run faster. Numba is a compiler for Python array and numerical functions. Cython is a way to program C extensions for Python using a syntax similar to Python.
Both frameworks should come with your conda installation. If not, and you get errors when running the instructions below, use
conda
orpip
to install them (see their websites linked above for instructions).Using Numba
calc_pi_numba.py
python calc_pi_numba.py
. How does the time compare to the original?Using Cython
Next, try to use Cython to approximate π. This part will be easier for users of Linux and macOS, as getting Cython to run on Windows is a little more involved.
We will use a notebook for this example, as it lets us see more information about how Cython works.
calc_pi_cython.ipynb
.%timeit
within the notebook to compare with the runtime of the Numba version and the original code.