Hacker News new | ask | show | jobs
by ProblemFactory 3218 days ago
> Of course, if there's a numpy function that does what you want, you'd use it in real life. But what if there isn't?

I have been in this exact situation, a numerical algorithm that was missing from Numpy but the rest of the project is in Python.

The solution is:

1. Write a Python function that operates on numpy arrays,

2. Add a few Cython type declarations to loop variables,

3. Mark the source file as "compile with Cython at runtime", which seamlessly turns the Python function into a C library.

The end result was a 1000x speedup compared to pure Python, very close to numpy built-in functions working on similarly sized arrays. And it needed only about 5 lines of setup code and type declarations for a few variables - all the code could still be Python and use all of Python even in the compiled files.