{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Part 3: Parallel programming with Cython\n", "\n", "Cython is an extension of the Python language which provides improved performance similar to compiled C-code. \n", "\n", "Cython is sometimes described as a hybrid-style language mixing Python and C, using C-like static type definitions to provide the Cython compiler with enough extra information to produce highly-performant code, offering performance similar to traditional compiled C code.\n", "\n", "In this mini-tutorial, we are going to look at a particular subset of the Cython project that provides parallel programming support, using the `cython.parallel` module.\n", "\n", "## A brief crash course in Cython\n", "\n", "Before we look at the `cython.parallel` module, however, we should cover some basic Cython first to get a feel of how it looks and works compared to pure Python and C code!\n", "\n", "Here is a programming example favourite - a function that computes the n-th Fibonacci number, taking `n` as its input argument.\n", "\n", "Here it is in __Python__:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def fib(n):\n", " a = 0.0\n", " b = 1.0\n", " for i in range(n):\n", " a, b = a + b, a\n", " return a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "All Python code is also valid Cython code, and has the same behaviour whether it is run through the Python interpreter, or compiled with the Cython compiler. Using the Cython compiler on the above code will not have much effect on its performance however, but here is where the special __Cython__ syntax comes in. \n", "\n", "As Cython is a kind of Python-C hybrid, let's consider what the above code would look like translated into __pure C__ code." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```C\n", "/* C version of the fibonacci calculation*/\n", "double fib(int n)\n", "{\n", " int i;\n", " double a = 0.0, b = 1.0, tmp;\n", " for (i=0; i