[Stackless] Video on channels

Johan Carlsson johanc at easypublisher.com
Wed Sep 12 13:07:53 CEST 2007

Starting to get of topic ;-D

A super stupid (almost all C like) PyRex version
of a simple imperative primes calculator (two versions,
with 10000 and 100000 pre-allocated integer arrays):

def primes(int kmax):
    cdef int n, k, i
    cdef int p[100000]
    result = []
    if kmax > 100000:
        kmax = 100000
    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
        n = n + 1
    return result

Was a tiny bit faster then OvermindDL1's C++ version:

4 function calls in 281.793 CPU seconds (for the 100K case)
(about 2 secs for the 10K)

Now for the PyRex Stackless case:

Ok, writting Stackless in PyRex was harder then I hope for
I can't pass around channels when accessing the C API of stackless
so I had to import the Python stackless instead and go that way.

import stackless

def counter(ch, int i):
    while True:
        i = i + 1

def filter(int p, object r, object s):
    cdef int x
    while True:
        x = r.receive()
        if x % p:

def applyfilter(object ch, int p):
    nch = stackless.channel()
    stackless.tasklet(filter)(p, ch, nch)
    return nch

def sieve(prime):

    ch = stackless.channel()
    stackless.tasklet(counter)(ch, 2)

    while True:
        p = ch.receive()
        ch = applyfilter(ch, p)

def run(goal = 100):

        primes = stackless.channel()

        for i in xrange(goal):
    except TaskletExit:

Note: I have removed the print statement in all my test.

>>> profile.run("s.run(10000)")
         4 function calls in 556.652 CPU seconds

Which is twice as slow as the imperative Python only case.
(I guess Stackless in PyRex is a bad idea? Don't know why yet.)
Johan Carlsson
Colliberty Easy Publisher

More information about the Stackless mailing list