The Mandelbrot Project

I’ve published the source code of the program I wrote for my tech talk at the 2011 PyDay conference. It’s a Python script and a companion C library that calculates and draws the Mandelbrot set.

The objective of the tech talk was to show how to speed up Python programs using the power of native code.


A render of the Mandelbrot set as performed by the mandelbrot.py script. Computations were performed in C.
A render of the Mandelbrot set as performed by the mandelbrot.py script. Computations were performed in C.

What’s interesting about this program is that, although the core was written completely in Python, I wrote two compute backends for it: one in Python and one in C. The C code is interfaced with using the ctypes module.

The results of running the program are shown in the screenshot above. If you are interested in trying it, the full source code is hosted in GitHub, here: https://github.com/alesegovia/mandelbrot. I’ve licensed it under the GPLv3, so you can download, run it, test it and modify it.

As one would anticipate, the C implementation runs much faster than the Python one, even when taking into account the marshaling of objects from Python to C and back. Here’s the chart I prepared for the conference showing the specific numbers from my tests.

These tests were performed to compare the run times at different numer of iterations, note this is a logarithmic scale.


Comparison of the Python + C implementation vs a pure Python one. Scale is Logarithmic.
Comparison of the Python + C implementation vs a pure Python one. Scale is Logarithmic.

As you can see, Python programs can be significantly sped up using ctypes, especially when we are dealing with compute-intensive operations.

It might be possible to speed up the Python implementation to improve its performance to some extent, and now that the source code is available under the GPL, you are encouraged to! I would always expect well-written C code to outperform the Python implementation, but I would like to learn about your results if you happen to give it a go.

Happy hacking!

2 thoughts on “The Mandelbrot Project

  1. Me resulta muy interesante ver un ejemplo con la interfaz de interacción C – Python. Gracias Ale por compartir!

    Abrazo

    1. De nada Martín! Si revisaste el código en github, habrás visto que no es nada de otro mundo! Hay otras formas de integrar Python con C que son un poco más complicadas, pero que también permiten exprimir más performance del código Python.

      Cython, en particular, es una herramienta que me gusta mucho. La idea fundamental es “anotar” el código Python con tipos de datos de C y luego pasarlo por un compilador que genera C usando PyObjects. Sacando ventaja de tus anotaciones, el compilador puede utilizar tipos nativos de C para operaciones críticas como loops y cuentas.

Comments are closed.