The Mandelbrot Set

I developed this project for my tech talk at the 2011 PyDay conference. It consists primarily of 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, and all the source code is available for free in GitHub!


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 its core is written completely in Python, I made 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!