Overloading Python math functions using Cython

Here is my main problem:

I have a Python file with import

from math import sin,cos,sqrt 

I need this file so that it is 100% compatible with CPython so that my developers can write 100% CPython code and use the great tools developed for Python.

Now log into Cython. In my Python file, trigger functions are called millions of times (fundamental to code, cannot change this). Is there a way that through some Python-fu in the main python file or in Cython magic otherwise I can use the C / C ++ math functions instead using some variations of Cython code

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

This will give me almost C-performance, which would be awesome.

Stefan talk says it can't be done, but talk two years, and there are a lot of creative people

+6
source share
3 answers

I'm not a Cython expert, but AFAIK, all you could do was write a Cython wrapper around sin and name it. I can’t imagine that it really will be faster than math.sin , although since it still uses Python call semantics - the overhead in all Python materials to call a function, not the actual trigger calculations that are done in C when using CPython also.

Do you consider using pure Cython mode , which makes the original CPython compatible?

+2
source

In the example from the Cython documentation, they use cimport from the C library to achieve this:

 from libc.math cimport sin 
+2
source

I may have misunderstood your problem, but the Cython documentation for interacting with external C code seems to offer the following syntax:

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

which gives the function the name sin in the C code (so that it correctly refers to the function from math.h ) and c_sin in the Python module. I'm not quite sure that I understand that this is achieved in this case, but why do you want to use math.sin in Cython code? Do you have some statically typed variables and some dynamically typed ones?

0
source

Source: https://habr.com/ru/post/914333/


All Articles