Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning Cython Programming (Second Edition)

You're reading from   Learning Cython Programming (Second Edition) Expand your existing legacy applications in C using Python

Arrow left icon
Product type Paperback
Published in Feb 2016
Publisher Packt
ISBN-13 9781783551675
Length 110 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Philip Herron Philip Herron
Author Profile Icon Philip Herron
Philip Herron
Arrow right icon
View More author details
Toc

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...
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 $19.99/month. Cancel anytime
Banner background image