Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learning Cython Programming (Second Edition) - Second Edition

You're reading from  Learning Cython Programming (Second Edition) - Second Edition

Product type Book
Published in Feb 2016
Publisher Packt
ISBN-13 9781783551675
Pages 110 pages
Edition 2nd Edition
Languages
Author (1):
Philip Herron Philip Herron
Profile icon Philip Herron

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 ...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}