Pyrex speed

Graham Breed x31equsenet at gmail.com
Sat May 27 15:46:46 CEST 2006


Jim Lewis \/\/|20+3:
> I'm not planning to write C functions. My understanding is that by
> using cdefs in the python code one can gain substantial speed. I'm
> trying to find a description of how to modify python code in more
> detail so it runs fast under pyrex.

I've used pyrex to speed up my code.  It worked.  While it isn't
intended as a tutorial on pyrex you can have a look at it here:

http://www.microtonal.co.uk/temper.html

The trick is to write C functions using pyrex.  That's not much easier
than writing C functions in C.  But I still found it convenient enough
to be worth doing that way.  Some tips:

- declare functions with cdef

- declare the type of every variable you use

- don't use Python builtins, or other libraries

The point of these rules is that generated C code using Python
variables will still be slow.  You want Pyrex to write C code using C
variables only.  To check this is happening you can look at the
automatically generated source code to make sure there are no reference
counting functions where there shouldn't be.

The usual rule for C optimization applies -- rewrite the code that
you're spending most time in.  But if that innermost function's being
called from a loop it can be worth changing the loop as well so that
you pass in and out C variables.

HTH,

             Graham




More information about the Python-list mailing list