Ondrej Certik wrote:
> On Thu, Oct 16, 2008 at 9:37 PM, Dag Sverre Seljebotn
> <[EMAIL PROTECTED]> wrote:
>> Ondrej Certik wrote:
>> ...
>>> Where func2 is:
>>>
>>> def func2(a, MyFunc mf):
>>>     cdef f2 f = mf.get_f()
>>>     return array([f(x) for x in a])
>>>
>>> This works nice. Is this the way to do it? Or is there some
>>> better/simpler way. I don't know if it's a good idea to make Cython
>>> clever enough to wrap things like this automatically?
>>
>> I think the way you did it is more than elegant enough :-) As others
>> have
>> commented, this is fine.
>>
>> This is just a note on performance: That list comprehension is really
>> going to kill performance. If you do this instead:
>>
>> def func2(np.ndarray[right_dtype_t, ndim=1] a, MyFunc mf):
>>    cdef f2 f = mf.get_f()
>>    cdef np.ndarray[right_dtype_t, ndim=1] result = np.empty(a.shape,
>> right_dtype)
>>    cdef unsigned int i
>>    for i in range(a.shape[0]):
>>        result[i] = f(a[i])
>>    return result
>>
>> ...then it should be much, much faster (avoiding conversion of every
>> single array element back and forth from/to Python objects).
>
> Thanks Dag! This is really useful, I was thinking how to do that
> efficiently. This is basically vectorise optimized for C functions.
>
> Maybe stuff like this could go to some numpy Cython file shipped with
> numpy? Those are things that are needed over and over again.

Feel free to propose it for them :-) (I don't have anything to do with
NumPy development myself.) We could probably ship Cython utility libraries
available together with Cython as well. Someone needs to write it though,
and I don't have the time for it.

Note: It is only a 1D vectorise. To work with multi-dimensional arrays
more complicated code is needed (NumPy generic nd-iterators using the
NumPy C API). Probably the NumPy C API has some code one could utilize.

That's the thing with NumPy -- things always get very generic when one
wants to create something that's usable beyond your own specific usecase.

Dag Sverre

_______________________________________________
Cython-dev mailing list
[email protected]
http://codespeak.net/mailman/listinfo/cython-dev

Reply via email to