Follow these steps to use Cython to greatly improve the performance of the code for generating an image of the Mandelbrot set:
- Start a new file called cython_mandel.pyx in the mandelbrot folder. In this file, we will add some simple imports and type definitions:
# mandelbrot/cython_mandel.pyx
import numpy as np
cimport numpy as np
cimport cython
ctypedef Py_ssize_t Int
ctypedef np.float64_t Double
- Next, we define a new version of the in_mandel routine using the Cython syntax. We add some declarations to the first few lines of this routine:
cdef int in_mandel(Double cx, Double cy, int max_iter):
cdef Double x = cx
cdef Double y = cy
cdef Double x2, y2
cdef Int i
- The rest of the function is identical to the Python version of the function:
for i in range(max_iter):
x2 = x**2
y2 = y**2
if (x2 + y2) >= 4:
return i
...