Extending python with C

eric eric at enthought.com
Sat May 4 00:35:53 EDT 2002


Hey Henrik,

You've put together a nice example.  Thanks for taking the time to write this
up.  I thought I'd also give an example of how to do the same thing using weave
which allows you to mix C++ directly into Python.

regards,
eric


C:\home\ej\examples>python weave_isprime.py
1230 67.8978202537
1230 2.70180455896

# weave_isprime.py

import weave

def py_isprime(input):
    if input < 1:
        return 0

    n = input-1

    while n > 1:
        if input%n == 0:
            return 0
        n = n - 1
    return 1

def isprime(input):
    c_code =\
    """
        int n;

        if (input < 1) {
            return Py::new_reference_to(Py::Int(0));
        }
        n = input - 1;

        while (n > 1){
            if (input%n == 0)
                return Py::new_reference_to(Py::Int(0));
            n--;
        }
        return Py::new_reference_to(Py::Int(1));
    """
    return weave.inline(c_code,['input'])

def time_prime(func,n):
    import time
    results = []
    t1 = time.clock()
    for i in range(n):
        if func(i):
            results.append(i)
    t2 = time.clock()
    print len(results), t2-t1

if __name__== "__main__":
    n = 10000
    time_prime(py_isprime,n)
    time_prime(isprime,n)

----- Original Message -----
From: "Henrik Härkönen" <radix at verso.st.jyu.fi>
Newsgroups: comp.lang.python
Sent: Friday, May 03, 2002 4:51 AM
Subject: Extending python with C


> Hi!
>
> I found that the possibility to extend Python with C is indeed very nice
> feature of Python! Exited by this, I made little testings how much speed
> up in some python programs can be accomplished. I also wrote a little
> 'note' about it, if anyone is interested, check
>
> http://kortis.to/radix/python_ext/
>
> It includes two graphs which shows the difference between a pure C program
> and a combination of Python and C.
>
> So far, Python has never stopped to amaze me how nice things really can be
> in programming today. :)
>
> --
> Henrik Härkönen <radix at kortis.to> [ http://kortis.to/radix ]







More information about the Python-list mailing list