Defining the types as np.ndarray mainly improves one thing: it makes indexing them to get single values significantly faster. Almost everything else remains the same speed.

np.cumsum (and any other Numpy function) is called through the standard Python mechanism and runs at exactly the same speed (internally of course it's implemented in C and should be quite quick). Mathematical operator (such add +, -, *, etc.) are also called through Python and remain the same speed.

In reality your wrapping probably makes it slower - it adds an unnecessary type-check (to make sure that the array is an np.ndarray) and an extra layer of indirection.

There is nothing to be gained through typing here.

Answer from DavidW on Stack Overflow
🌐
Google Groups
groups.google.com › g › cython-users › c › KXZti9XtR_w
How to import numpy types in cython pure python mode
June 28, 2021 - Anyhoozle, to answer your questions 1) yes pxd files can be used to write in how cython should interpret your python code · 2) locals can be used either separate or in conjuction with this pxd file (see docs for more). In your original code the cimport was wrong (again see docs). Cimport keyword is not directly available in pure python mode; for that you would need a pyx file. You can, however, import numpy via the provided wrapper `from cython.cimport import numpy as np` (as I did).
Discussions

Speed-up with Cython and Numpy/Scipy?
Cython is smart enough to understand numpy ndarrays and operate with them efficiently, so you can use them both together. As to how much speedup you'll get ... that is highly dependent on your code. I have certainly seen 2x improvements for suitably marked up Cython/numpy code over straight Python/numpy, but it really depends on where most of your work is. If it's all tight loops over numpy functions then you'll probably see little to no improvement. It really depends. Profile your code and see what is taking up the time. More on reddit.com
🌐 r/Python
8
2
August 14, 2013
python - Use numpy with Cython - Stack Overflow
I want to create .so file from python and execute the .so file in C. To do it I used cython to convert .pyx to .so ## print_me.pyx cimport numpy as cnp import numpy as np cimport cython cpdef pub... More on stackoverflow.com
🌐 stackoverflow.com
Performance comparison: Numpy vs. Cython vs Numba vs Pythran vs Julia
Really interesting, we use Cython for the core of the main functions but it is true that Pythran looks like a strong contender. The more I look into it the more I like it. More on reddit.com
🌐 r/Python
2
9
June 9, 2021
A comparison of Numpy, NumExpr, Numba, Cython, TensorFlow, PyOpenCl, and PyCUDA to compute Mandelbrot set
Great analysis, the results were eye opening. I've been wanting to checkout Numba for some time and I'll try to use it in my next project. More on reddit.com
🌐 r/Python
98
310
January 11, 2016
🌐
Cython
cython.readthedocs.io › en › latest › src › userguide › numpy_tutorial.html
Cython for NumPy users — Cython 3.3.0a0 documentation
So what made those line so much slower than in the pure Python version? array_1 and array_2 are still NumPy arrays, so Python objects, and expect Python integers as indexes. Here we pass C int values. So every time Cython reaches this line, it has to convert all the C integers to Python int objects.
🌐
Uio-in3110
uio-in3110.github.io › lectures › mixed-programming › mixed_programming_cython.html
Cython — Higher Level Programming 2023
Cython uses “typed memoryviews” for generating efficient C code for working with the data in numpy arrays. Below is the translation table between Python and Cython dypes:
🌐
GitHub
github.com › cython › cython › blob › master › docs › examples › userguide › numpy_tutorial › numpy_and_cython.ipynb
cython/docs/examples/userguide/numpy_tutorial/numpy_and_cython.ipynb at master · cython/cython
" compare_time(run_time, np_time, \"NumPy\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Pure Python version compiled with Cython:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true ·
Author   cython
🌐
Thomasjpfan
thomasjpfan.com › 2023 › 08 › quick-numpy-ufuncs-with-cython-30
Quick NumPy UFuncs with Cython 3.0 - thomasjpfan.com
There are many exciting features such as a Pure Python Mode and Initial support for Python's Limited API. In this blog post, we use Cython 3.0's @cython.ufunc decorator to quickly generate a NumPy Universal function ...
Find elsewhere
🌐
Readthedocs
cython-docs2.readthedocs.io › en › latest › src › tutorial › numpy.html
Using Cython with NumPy — Cython 0.15pre documentation
import numpy as np cimport numpy as np def myfunc(np.ndarray[np.float64_t, ndim=2] A): <...> myfunc can now only be passed two-dimensional arrays containing double precision floats, but array indexing operation is much, much faster, making it suitable for numerical loops. Expect speed increases well over 100 times over a pure Python loop; in some cases the speed increase can be as high as 700 times or more.
🌐
Reddit
reddit.com › r/python › speed-up with cython and numpy/scipy?
r/Python on Reddit: Speed-up with Cython and Numpy/Scipy?
August 14, 2013 -

Hey everyone. Maybe this has been asked and answered before, but I wasn't able to find a simple answer to this question. I'm wanting to use Python to write some scientific computing stuff, and of course Numpy and Scipy are awesome for that. But I had also read that Cython lets you easily write C extensions for Python code that can speed your results up enormously (something that would be really useful). I saw lots of results for "plain Python --> Cython," but wasn't able to find many benchmarks and/or results for Cython'ing code using Numpy and Scipy. Should I expect dramatic speed-ups with those, too?

🌐
Cython
docs.cython.org › en › latest › src › userguide › numpy_ufuncs.html
Creating Numpy ufuncs — Cython 3.3.0a0 documentation
Pure Python syntax which allows static Cython type declarations in pure Python code, following PEP-484 type hints and PEP 526 variable annotations.
🌐
Cython
cython.readthedocs.io › en › latest › src › tutorial › numpy.html
Working with NumPy — Cython 3.3.0a0 documentation
They are easier to use than the buffer syntax below, have less overhead, and can be passed around without requiring the GIL. They should be preferred to the syntax presented in this page. See Cython for NumPy users. ... There is currently no way to usefully specify Numpy arrays using Python-style ...
🌐
Readthedocs
notes-on-cython.readthedocs.io › en › latest › std_dev.html
The Performance of Python, Cython and C on a Vector — Cython def, cdef and cpdef functions 0.1.0 documentation
# Pure Python python3 -m timeit -s "import StdDev; import numpy as np; a = [float(v) for v in range(1000000)]" "StdDev.pyStdDev(a)" # Numpy python3 -m timeit -s "import StdDev; import numpy as np; a = np.arange(1e6)" "StdDev.npStdDev(a)" # Cython - naive python3 -m timeit -s "import cyStdDev; import numpy as np; a = np.arange(1e6)" "cyStdDev.cyStdDev(a)" # Optimised Cython python3 -m timeit -s "import cyStdDev; import numpy as np; a = np.arange(1e6)" "cyStdDev.cyOptStdDev(a)" # Cython calling C python3 -m timeit -s "import cyStdDev; import numpy as np; a = np.arange(1e6)" "cyStdDev.cStdDev(a)"
🌐
Cython
cython.readthedocs.io › en › latest › src › tutorial › pure.html
Pure Python Mode - Cython's Documentation - Read the Docs
Cython specific cdef syntax, which was designed to make type declarations concise and easily readable from a C/C++ perspective. Pure Python syntax which allows static Cython type declarations in pure Python code, following PEP-484 type hints and PEP 526 variable annotations.
Top answer
1 of 2
5

You must initialize the numpy C API by calling import_array().

Add this line to your cython file:

cnp.import_array()

And as pointed out by @user4815162342 and @DavidW in the comments, you must call Py_Initialize() and Py_Finalize() in main().

2 of 2
0

Thank you for your help first. I could get something useful information, even though that could not directly solve my problem.

By referring to others advice, rather than calling print_me function from .so file, I decided to call directly from C. This is what I did.

# print_me.pyx
import  numpy as np
cimport numpy as np

np.import_array()

cdef public char* print_me(f):
    cdef int[2][4] ll = [[1, 2, 3, 4], [5,6,7,8]]
    cdef np.ndarray[np.int_t, ndim=2] nll = np.zeros((4, 6), dtype=np.int)
    print nll
    nll += 1
    print nll
    return f + str(ll[1][0])

This is my .c file

// main.c
#include <python2.7/Python.h>
#include "print_me.h"

int main()
{
    // initialize python
    Py_Initialize();
    PyObject* filename = PyString_FromString("hello");
    initsquare_number();
    //initprint_me();

    // call python-oriented function
    printf("%s\n", print_me(filename));

    // finalize python
    Py_Finalize();
    return 0;
}

I compiled then as follows

# to generate print_me.c and print_me.h
cython print_me.pyx

# to build main.c and print_me.c into main.o and print_me.o
cc -c main.c print_me.c -I/usr/include/python2.7 -I/usr/lib64/python2.7/site-packages/numpy/core/include

# to linke .o files
cc -lpython2.7 -ldl main.o print_me.o -o main

# execute main
./main

This results the following

[[0 0 0 0 0 0]
 [0 0 0 0 0 0]
 [0 0 0 0 0 0]
 [0 0 0 0 0 0]]
[[1 1 1 1 1 1]
 [1 1 1 1 1 1]
 [1 1 1 1 1 1]
 [1 1 1 1 1 1]]
hello5

Thank you for all of your help again!! :)

🌐
GitHub
github.com › cython › cython › blob › master › docs › src › userguide › numpy_tutorial.rst
cython/docs/src/userguide/numpy_tutorial.rst at master · cython/cython
To add types we use custom Cython syntax, so we are now breaking Python source compatibility. Read the comments! .. tabs:: .. group-tab:: Pure Python .. literalinclude:: ../../examples/userguide/numpy_tutorial/compute_typed.py :caption: compute_typed.py .. figure:: compute_typed_py_html.png ..
Author   cython
🌐
Quora
quora.com › How-can-NumPy-be-used-with-Python-and-Cython-Which-is-faster-NumPy-or-the-built-in-functions-of-SciPy
How can NumPy be used with Python and Cython? Which is faster, NumPy or the built-in functions of SciPy? - Quora
Answer: Alright, let me break this down for you based on my experience with NumPy, Python, and Cython. NumPy is super useful when you're working with Python, especially for numerical computations. It's like Python's supercharged math library. You can use it to create and manipulate arrays, do li...
🌐
FutureLearn
futurelearn.com › home › blog
Using NumPy with Cython
October 25, 2022 - cimport numpy as cnp import cython ...
🌐
Peterbaumgartner
peterbaumgartner.com › blog › an introduction to just enough cython to be useful
An Introduction to Just Enough Cython to be Useful | Peter Baumgartner
March 1, 2022 - We have a python list that we don’t know the length of and can contain any type of object, and in this example we did not type depth, so we have to infer it’s type and convert current_depth—a C int—back to a python int to make the comparison. Arrays in numpy have the exact features to address our slowdowns: they’re of a fixed size and every element is the same type. They’re also easy to work with in Cython.
🌐
Cython
cython.readthedocs.io › en › stable › src › tutorial › pure.html
Pure Python Mode — Cython 3.2.2 documentation
The magic cython.cimports package provides a way to cimport external compile time C declarations from code written in plain Python. For convenience, it also provides a fallback Python implementation for the libc.math module. However, it is normally not possible to call C functions in pure Python code as there is no general way to represent them in normal (uncompiled) Python.
🌐
InfoWorld
infoworld.com › home › software development › programming languages › python
Use Cython to accelerate array iteration in NumPy | InfoWorld
August 31, 2022 - The most common scenario for using ... in NumPy. Cython works by letting you write modules in a type-annotated version of Python, which are then compiled to C and imported into your Python script like any other module....