Extending Python: rewriting a single method in C
Jeff Epler
jepler at inetnebr.com
Mon Mar 12 09:28:31 EST 2001
On 12 Mar 2001 11:13:51 +0000, Jacek Generowicz
<jmg at ecs.soton.ac.uk> wrote:
>I have an object-oriented numerical code written in Python. It has
>come to the stage where the speed of the code is seriously impeding
>progress. Profiling reveals (surprise, surprise) that most of the time
>is spent in only 2 methods.
>
>Is there any way of re-writing just these methods in C ?
It's easy to write a function in C. Other posters have mentioned references
to documentation about doing this.
However, you cannot make a builtin function be a method of a class/instance.
Instead, you could write:
from cmodule import fast_a, fast_b
class fastKlass(Klass):
def a(self, int1, int2):
fast_a(self, int1, int2)
def b(self, int1, int2):
fast_b(self, int1, int2)
In fast_a and fast_b, you can get arguments by using the ParseTuple string
"(Oii)" and then use PyObject_SetAttrString and PyObject_GetAttrString
to store or retrieve attributes (including, if necessary, instance
methods) from the instance by their name.
Note that if there are *many* calls to the method, rather than each
invocation taking a large amount of time, then this approach is not
going to gain you much, since it actually *increases* the function-call
overhead.
Jeff
More information about the Python-list
mailing list