Cython pure Python code
Let's view a mathematical application that is actually taken from the Cython documentation. I wrote this equivalent in pure Python so that we can compare the speed. If you open the primes
example for this chapter, you will see two programs—the Cython primes.pyx
example, and my pure Python port. They both look almost the same:
def primes(kmax): n = 0 k = 0 i = 0 if kmax > 1000: kmax = 1000 p = [0] * kmax result = [] k = 0 n = 2 while k < kmax: i = 0 while i < k and n % p[i] != 0: i = i + 1 if i == k: p[k] = n k = k + 1 result.append(n) n = n + 1 return result primes (10000)
This really is a direct Python port of that Cython code. Both call primes (10000)
, but the evaluation time is very different between them in terms of performance:
$ make
cython --embed primes.pyx
gcc -g -O2 -c primes.c -o primes.o `python-config --includes`
gcc ...