Notes on f2py and cython¶
- f2py takes source Fortran code and compiles it to a Python-readable module.
- Cython takes Python code and compiles it to C, which means the module will run faster.
Compiling Fortran code¶
Fortran code is compiled into a Python-readable .pyd
file using the package
f2py
. This can be done either from the command line, e.g.
f2py -c -m helloworld_fortran helloworld_fortran.f90
or from within a Python file using f2py2e
. We use the former option in this
repo.
To check that you can compile and load fortran modules, you will compile the
simple helloworld_fortran.f90
module included in this repo. The module has a
single subroutine called fortran_greetings
that will be turned into a Python
function.
Cythonizing Python code¶
This procedure takes Python code and turns it into a compiled .pyd
module,
which means it is potentially much faster.
You can cythonize either in your setup.py
file or from the command line.
We’ll use the latter, because we had trouble getting the inplace
flag to work,
which meant that the .pyd
files were in the wrong place.
The terminal command to cythonize code (assuming you have Cython installed and correctly configured compilers) is
cythonize -a -i helloworld_cython.pyx
To check that you can cythonize python code, you will compile the
helloworld_cython.pyx
module included in this repo. The module has a
single subroutine called cython_greetings
that will be turned into a Python
function.