Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading Python math functions using Cython

Tags:

python

cython

Here is my basic problem:

I have a Python file with an import of

from math import sin,cos,sqrt

I need this file to still be 100% CPython compatible to allow my developers to write 100% CPython code and employ the great tools developed for Python.

Now enter Cython. In my Python file, the trig functions get called millions of times (fundamental to the code, can't change this). Is there any way that through some Python-fu in the main python file, or Cython magic otherwise I can instead use the C/C++ math functions using some variation on the Cython code

cdef extern from "math.h":
    double sin(double)

That would give me near-C performance, which would be awesome.

Stefan's talk says specifically this can't be done, but the talk is two years old, and there are many creative people out there

like image 829
ibell Avatar asked Apr 27 '12 12:04

ibell


2 Answers

In an example from Cython's documentation, they use a cimport from a C library to achieve this:

from libc.math cimport sin
like image 70
Brett Morris Avatar answered Oct 23 '22 04:10

Brett Morris


I'm not a Cython expert, but AFAIK, all you could do is write a Cython wrapper around sin and call that. I can't imagine that's really going to be faster than math.sin, though, since it's still using Python calling semantics -- the overhead is in all the Python stuff to call the function, not the actual trig calculations, which are done in C when using CPython too.

Have you considered using Cython pure mode, which makes the source CPython-compatible?

like image 40
Danica Avatar answered Oct 23 '22 05:10

Danica